Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How a Local First-Time Tracker Works in Chrome MV3

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide explains how a local first-time tracker works in a Chrome extension built with Manifest V3 (MV3). You'll learn how to store a flag in chrome.storage.local so your extension can tell whether a user has run it before, and how to act on that information. This is useful for showing onboarding screens, granting one-time bonuses, or triggering a first-run setup. No server is needed—everything stays on the user's device.

What You'll Need

  • Basic knowledge of JavaScript and Chrome extension structure (manifest.json, background service worker, popup or content script).
  • Chrome browser (any recent version that supports MV3, i.e., Chrome 88+).
  • A text editor to create the extension files.
  • Optional: Chrome's chrome://extensions page for loading unpacked extensions.

Step-by-Step

  1. Create your extension folder. Make a new directory, e.g., my-extension, and inside it create a manifest.json file. This is the heart of your MV3 extension.
  2. Write the manifest. At minimum, include the manifest version, name, version, and the permissions you need. For local storage, you must request the storage permission. A minimal manifest.json looks like:
    {
      "manifest_version": 3,
      "name": "My Tracker Extension",
      "version": "1.0",
      "permissions": ["storage"],
      "background": {
        "service_worker": "background.js"
      },
      "action": {
        "default_popup": "popup.html"
      }
    }
    The storage permission is essential—without it, chrome.storage.local will be undefined.
  3. Create the background service worker. In background.js, you'll handle the first-run logic. This script runs in the background and can access chrome.storage. A basic service worker for first-run tracking might look like:
    chrome.runtime.onInstalled.addListener(() => {
      chrome.storage.local.get(['hasRunBefore'], (result) => {
        if (!result.hasRunBefore) {
          // First run: set the flag and do something special
          chrome.storage.local.set({ hasRunBefore: true }, () => {
            console.log('First run detected. Flag set.');
            // You could open a welcome tab, show a notification, etc.
          });
        } else {
          console.log('Returning user.');
        }
      });
    });
    The onInstalled event fires when the extension is installed or updated. This is a good place to check the flag because it runs once per install/update.
  4. Check the flag in other parts of the extension. You might want to check the flag in your popup or content script to decide what UI to show. For example, in popup.js:
    chrome.storage.local.get(['hasRunBefore'], (result) => {
      if (result.hasRunBefore) {
        document.getElementById('welcome').style.display = 'none';
        document.getElementById('main').style.display = 'block';
      } else {
        document.getElementById('welcome').style.display = 'block';
        document.getElementById('main').style.display = 'none';
      }
    });
    This reads the flag and toggles visibility accordingly.
  5. Test your extension. Go to chrome://extensions, enable Developer mode (toggle in the top right), click "Load unpacked", and select your extension folder. After loading, you should see the console log from the service worker (right-click the extension icon and select "Inspect" to open the service worker console).
  6. Reset the flag for testing. To test the first-run experience again, you can clear the storage. In the service worker console, run chrome.storage.local.clear() and then reload the extension (click the refresh icon on the extension card). This resets the flag so you can see the first-run behavior again.

Common Mistakes

  • Forgetting the storage permission. Without it, chrome.storage is undefined and you'll get errors.
  • Using chrome.storage.sync instead of local. Sync is for data that should sync across devices; for a local first-time tracker, you want local to keep it device-specific.
  • Checking the flag in the wrong place. If you check it in a popup that opens every time, you might get race conditions if the flag isn't set yet. Use onInstalled for setting, and read it in other parts with callbacks.
  • Assuming the callback is synchronous. chrome.storage calls are asynchronous. Always use the callback or await (in async functions) to get the value.
  • Not handling updates. onInstalled fires on updates too. If you want to reset the flag on update, you can check details.reason to distinguish between install and update.

Tips

  • Use a more descriptive key than hasRunBefore, like firstRunCompleted, to avoid confusion.
  • If you need to store more data (like a timestamp), you can store an object: { firstRun: true, timestamp: Date.now() }.
  • For debugging, log the result of chrome.storage.local.get to see what's stored.
  • Consider using chrome.storage.local.set with a callback to ensure the write completes before proceeding.
  • If you're using a content script, remember to declare it in the manifest and include the storage permission as well.

Troubleshooting

  • Extension doesn't load: Check the manifest for syntax errors. Open chrome://extensions and look for a red error message on your extension card.
  • chrome.storage is undefined: Make sure you added "permissions": ["storage"] to the manifest and reloaded the extension.
  • Flag not set: Check the service worker console for errors. Make sure the onInstalled listener is registered correctly. Also, if you're testing by reloading the extension, note that reloading doesn't fire onInstalled again—only install/update does.
  • Flag resets unexpectedly: If you clear browser data or uninstall/reinstall the extension, the local storage is cleared. That's expected behavior.
  • Race condition between reading and writing: If you're setting the flag in one place and reading in another, ensure the write completes before the read. Use callbacks or promises (wrap in async/await) to sequence operations.

Frequently Asked Questions

  1. Does this work in Manifest V2? Yes, the chrome.storage.local API is the same in MV2, but the background script structure differs (background pages instead of service workers). This guide focuses on MV3.
  2. Can I use localStorage instead? In a background service worker, localStorage is not available (it's for pages). In popup or content scripts, localStorage works but is tied to the origin and can be cleared by the user. chrome.storage.local is more reliable for extensions.
  3. How do I reset the flag for testing? Use chrome.storage.local.clear() in the service worker console, then reload the extension (not just the popup).
  4. What if the user clears browser data? chrome.storage.local is cleared when the user clears browsing data (including cookies and site data). That's fine—the first-run experience will appear again.
  5. Can I store the flag in chrome.storage.sync instead? Yes, but sync storage is limited to 100KB and is shared across devices. For a local-only flag, local is better.
  6. Does the flag persist after an extension update? Yes, chrome.storage.local persists across updates unless you explicitly clear it. However, onInstalled fires on update, so you can decide whether to reset it based on details.reason.