Build a Browser Extension for Usage Tracking

Tracking API usage manually can be frustrating, especially when dealing with rate limits and daily reset windows. A common complaint is that users lose track of their remaining tokens or miss the exact moment their quota resets. This guide walks through creating a lightweight Chrome extension that displays your current usage and the countdown to reset directly on the screen, eliminating the need to dig into settings pages.
The solution involves building a minimal extension that injects a floating widget into your workflow. This widget fetches real-time data from the API, calculates the time remaining until the daily reset, and displays your token consumption. By keeping this information visible, you can manage your requests more effectively and avoid unexpected interruptions during coding sessions or data processing tasks.
We will cover the core components: manifest configuration, background scripts for data fetching, and content scripts for UI injection. The extension respects the free tier limits, which include a burst capacity and a daily reset at midnight UTC. You will learn how to handle CORS, parse JSON responses, and update the DOM efficiently without blocking the main thread. This approach works for any OpenAI-compatible endpoint, making it versatile for various API providers.
Frequently asked questions
What is a usage monitor extension?
A usage monitor extension is a browser add-on that tracks API consumption in real time. It displays remaining tokens, rate limit status, and reset countdowns directly in the UI, helping users manage their quota without switching contexts or checking external dashboards manually.
How does a floating widget differ from a sidebar?
A floating widget is a small, draggable overlay that stays on top of other content, providing quick access to usage stats without obstructing the main workspace. A sidebar occupies a fixed column, which can reduce available screen real estate, especially on smaller monitors or when viewing wide code panels.
Which is better for real-time tracking: polling or webhooks?
Polling is simpler to implement and works well for low-frequency updates like daily resets. Webhooks offer instant notifications but require more complex server-side infrastructure. For a browser extension tracking local quota limits, polling every few seconds is usually sufficient and easier to debug.
How does the extension handle CORS restrictions?
The extension uses the browser's fetch API with the correct headers. Since the API supports CORS, the extension can request data directly. If CORS is not enabled, the extension can use a background script to proxy the request, ensuring the data reaches the content script without cross-origin errors.
What is the daily reset time for the free tier?
The free tier quota resets at 00:00 UTC daily. The extension calculates the time remaining until this reset and displays a countdown timer. This helps users plan their requests to avoid hitting the limit before the window closes, ensuring continuous access to the model.
How does the extension detect rate limit errors?
The extension monitors HTTP response codes, specifically 429 for too many requests. When a 429 is detected, the widget updates to show the Retry-After header value, indicating how long to wait before making another request. This prevents spamming the API and helps manage burst limits effectively.
Can the extension track multiple API keys?
Yes, the extension can be configured to track multiple keys by storing them in the browser's local storage. Each key can have its own usage counter and reset timer. This is useful for developers managing different projects or testing different endpoints simultaneously.
Why is the domain not affiliated with Google?
The domain contains the brand Gemini but the site is not affiliated with Google: the free-ai model is an independent open-weight model. The extension tracks usage for the specific API endpoint provided, which may differ from Google's proprietary models, so it is important to verify the source of the API requests.
Step by step
- Create Manifest — Define permissions and background scripts in manifest.json to enable storage and API access.
- Fetch Data — Implement fetch logic to retrieve usage data from the API endpoint and parse JSON responses.
- Inject Widget — Create and inject a floating widget into the DOM, styling it to match the page layout.
- Update Timer — Calculate and display the reset countdown, updating the UI every second with the remaining time.
- Handle Errors — Detect 429 errors and display the Retry-After header, disabling refresh until the wait time expires.
- Test Locally — Use Chrome DevTools to verify network requests, storage data, and UI updates in different scenarios.
Setting Up the Extension Manifest
The foundation of any Chrome extension is the manifest file, which defines permissions, scripts, and UI elements. For our usage monitor, we need permissions to access storage, make network requests, and inject content scripts into specific domains. The manifest version 3 is the current standard, offering better performance and security features.
We start by creating a manifest.json file with the necessary permissions. This includes storage for saving user preferences and usage data, and activeTab or specific host permissions for the API endpoint. The manifest also defines the background service worker, which handles the heavy lifting of data fetching and state management.
Manifest Permissions Explained
Permissions like storage, activeTab, and host permissions are crucial for the extension to function correctly. Storage allows us to persist user settings and usage data across sessions. ActiveTab enables the extension to interact with the current tab, while host permissions allow it to make requests to the API endpoint.
Service Worker Configuration
The background service worker acts as the brain of the extension. It handles API requests, updates the UI, and manages the timer for the daily reset. By using a service worker, we ensure that the extension remains responsive and efficient, even when the user is not actively interacting with it.
- storage: Save usage data and settings
- activeTab: Access current tab content
- host_permissions: Make API requests
{
"manifest_version": 3,
"name": "Usage Monitor",
"version": "1.0",
"permissions": ["storage", "activeTab"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}Fetching Usage Data from the API
The extension needs to fetch real-time usage data from the API. This involves making HTTP requests to the /health or /v1/models endpoint to get current usage statistics. The API returns JSON data, which the extension parses to update the UI. It is important to handle errors gracefully, especially when the API is busy or rate-limited.
We use the fetch API to make GET requests to the API endpoint. The response is parsed as JSON, and the usage data is extracted. This data is then stored in the browser's local storage for later use. The extension also calculates the time remaining until the daily reset, which is a key feature for users.
API Request Structure
The API request is a simple GET request to the /health endpoint. This endpoint returns the current status of the API, including usage statistics and rate limit information. The request includes a User-Agent header to identify the extension, which helps with logging and debugging.
Parsing JSON Responses
The JSON response is parsed using the JSON.parse method. The usage data, such as tokens used and remaining, is extracted from the response. This data is then used to update the UI and store the current state in local storage. Error handling is implemented to catch any network issues or invalid responses.
async function fetchUsageData() {
try {
const response = await fetch('https://api.geminikeyapifree.com/v1/health');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}
Injecting the Floating Widget
The floating widget is a small overlay that displays usage data directly on the screen. It is injected into the DOM using a content script, which runs in the context of the current page. The widget is designed to be minimal and non-intrusive, providing quick access to usage stats without obstructing the main content.
The widget includes a timer for the daily reset, a display of remaining tokens, and a button to refresh the data. It is draggable and can be resized by the user. The widget is styled with CSS to match the look and feel of the page, ensuring a seamless user experience. The content script handles the creation and positioning of the widget.
Widget DOM Structure
The widget is created as a div element with specific classes for styling. It contains elements for the timer, token count, and refresh button. The structure is simple and semantic, making it easy to style and interact with. The widget is appended to the body of the page, positioned absolutely to float over other content.
Styling and Positioning
CSS is used to style the widget, ensuring it is visually distinct and easy to read. The widget is positioned absolutely, allowing it to be placed anywhere on the screen. JavaScript handles the positioning, ensuring it does not overlap with other elements. The widget is also made draggable, allowing users to move it to a convenient location.
- div.widget-container: Main wrapper
- span.timer: Reset countdown
- span.tokens: Usage display
function createWidget() {
const widget = document.createElement('div');
widget.className = 'usage-widget';
widget.innerHTML = `
<div class="widget-header">
<span class="timer">00:00:00</span>
<button class="refresh-btn">Refresh</button>
</div>
<div class="widget-body">
<span class="tokens">Tokens: 0</span>
</div>
`;
document.body.appendChild(widget);
return widget;
}Calculating the Reset Countdown
The daily reset occurs at 00:00 UTC. The extension calculates the time remaining until this reset by comparing the current time with the reset time. This calculation is performed every second to provide a real-time countdown. The result is displayed in the widget, updating the timer continuously.
The calculation involves getting the current date and time, and then determining the difference between this time and the next reset time. The difference is converted into hours, minutes, and seconds, which are then formatted and displayed in the widget. This feature helps users plan their requests to avoid hitting the limit.
Time Calculation Logic
The logic involves getting the current UTC time and adding one day to it. The difference between the current time and the next reset time is calculated in milliseconds. This value is then converted into hours, minutes, and seconds for display. The calculation is performed every second to keep the timer accurate.
Timer Update Mechanism
A setInterval function is used to update the timer every second. The function recalculates the time remaining and updates the DOM element displaying the timer. This ensures that the user always sees the correct countdown, helping them manage their usage effectively. The timer is paused when the widget is hidden or the page is unloaded.
function updateTimer() {
const now = new Date();
const nextReset = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1, 0, 0, 0);
const diff = nextReset - now;
const hours = Math.floor(diff / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
document.querySelector('.timer').textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
Handling Rate Limit Errors
When the API returns a 429 status code, it indicates that the rate limit has been exceeded. The extension detects this error and updates the widget to show the Retry-After header value. This value indicates how long the user should wait before making another request. This helps prevent spamming the API and ensures efficient usage.
The extension parses the Retry-After header from the response and displays it in the widget. The timer is paused until the specified time has passed, after which the widget automatically refreshes the data. This feature is crucial for managing burst limits and avoiding unnecessary errors during high-frequency requests.
Detecting 429 Errors
The fetch request checks the response status code. If it is 429, the extension extracts the Retry-After header. This header value is parsed and stored in the widget's state. The widget then displays this value to the user, indicating the wait time before the next request can be made.
Updating UI on Rate Limit
When a 429 error is detected, the widget updates its display to show the retry time. The refresh button is disabled until the retry time has passed. This prevents the user from manually refreshing and getting another 429 error. The widget also provides visual feedback, such as a red highlight, to indicate the rate limit status.
- status === 429: Rate limit exceeded
- Retry-After header: Wait time
- UI update: Show retry time
async function fetchUsageData() {
try {
const response = await fetch('https://api.geminikeyapifree.com/v1/health');
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
updateRetryUI(retryAfter);
return null;
}
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}Managing Local Storage
The extension uses the browser's local storage to persist usage data and settings. This allows the extension to retain information across page reloads and browser restarts. The local storage is used to store the current usage count, the last reset time, and user preferences such as widget position and visibility.
Data is saved to local storage after each API request or when the user updates a setting. The extension reads this data on startup to restore the previous state. This ensures a seamless experience for the user, who does not need to re-enter information or wait for the extension to recalculate data.
Storage Keys and Values
The extension uses specific keys for different types of data, such as 'usageCount', 'lastResetTime', and 'widgetPosition'. Each key is associated with a value that is serialized as a string. This structure makes it easy to manage and retrieve data from local storage.
Data Persistence Strategy
Data is persisted after every update to ensure that the latest state is always saved. The extension also implements a cleanup routine to remove old data if necessary. This helps prevent the local storage from becoming cluttered and ensures that the extension remains efficient over time.
function saveUsageData(data) {
chrome.storage.local.set({
usageCount: data.tokens,
lastResetTime: new Date().toISOString()
}, () => {
console.log('Usage data saved');
});
}
function loadUsageData() {
return new Promise((resolve) => {
chrome.storage.local.get(['usageCount', 'lastResetTime'], (result) => {
resolve(result);
});
});
}
Optimizing Performance
Performance is critical for a smooth user experience. The extension minimizes DOM manipulation by updating only the necessary elements. It also debounces rapid API requests to avoid overwhelming the browser. The extension uses efficient algorithms for time calculations and DOM updates, ensuring that it runs smoothly even on low-end devices.
The extension also implements lazy loading for the widget, which means it is only created when the user navigates to a relevant page. This reduces the initial load time and resource usage. The widget is also optimized for accessibility, with proper ARIA labels and keyboard navigation support.
DOM Update Optimization
Instead of updating the entire widget on every change, the extension updates only the specific elements that have changed. This reduces the number of DOM operations, which can be expensive. The extension also uses requestAnimationFrame to batch DOM updates, ensuring smooth rendering.
Debouncing API Requests
A debounce function is used to delay API requests until the user has stopped interacting with the widget. This prevents rapid-fire requests when the user is dragging or resizing the widget. The debounce function ensures that only the final request is made, reducing network traffic and improving performance.
- requestAnimationFrame: Batch DOM updates
- debounce: Delay API requests
- lazy loading: Reduce initial load
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
const debouncedFetch = debounce(fetchUsageData, 500);Testing and Debugging
Testing the extension involves simulating various scenarios, such as rate limits, network errors, and page reloads. The extension is tested in different browsers to ensure compatibility. Debugging tools like Chrome DevTools are used to monitor network requests, storage data, and DOM changes. This helps identify and fix issues quickly.
The extension also includes logging functionality to record errors and unusual behavior. These logs can be accessed via the background service worker's console. This makes it easier to diagnose issues reported by users and improve the extension over time. Regular testing ensures that the extension remains reliable and user-friendly.
Simulating Rate Limits
To test rate limit handling, the extension can be configured to return a 429 status code from a mock server. This allows developers to verify that the widget correctly displays the retry time and disables the refresh button. The test ensures that the extension behaves as expected under load.
Using Chrome DevTools
Chrome DevTools provides a suite of tools for debugging extensions. The Application tab shows local storage data, the Network tab monitors API requests, and the Console logs errors and warnings. These tools are essential for diagnosing issues and optimizing performance. Developers can also use the Service Workers panel to inspect the background script.
console.log('Extension loaded');
chrome.runtime.onInstalled.addListener(() => {
console.log('Extension installed');
});
chrome.storage.local.get(['usageCount'], (result) => {
console.log('Usage count:', result.usageCount);
});
Test the model instantly with our keyless endpoint—no credit card, no setup required.