Chrome Extension Action on Browser Start

Learn chrome extension action on browser start with practical examples, diagrams, and best practices. Covers javascript, google-chrome, events development techniques with visual explanations.

Executing Chrome Extension Actions on Browser Startup

Illustration of a Chrome browser icon with an extension icon overlayed, symbolizing automatic startup actions.

Learn how to configure your Chrome Extension to perform actions automatically when the browser starts, ensuring your extension's functionality is available from the moment Chrome launches.

Chrome Extensions offer powerful ways to enhance browser functionality. A common requirement for many extensions is to perform certain actions or initialize states as soon as the browser launches. This article will guide you through the process of setting up your Chrome Extension to execute code reliably on browser startup, leveraging the chrome.runtime.onStartup event.

Understanding the chrome.runtime.onStartup Event

The chrome.runtime.onStartup event is specifically designed for extensions to run code when the browser starts. This event fires when a profile that has the extension enabled is first started, or when the browser is restarted. It's crucial to understand that this event is distinct from chrome.runtime.onInstalled, which only fires once when the extension is first installed or updated. onStartup ensures your extension can re-establish its state or perform initial setup every time the browser is launched.

flowchart TD
    A[Browser Starts] --> B{Extension Enabled?}
    B -- Yes --> C["chrome.runtime.onStartup" Event Fired]
    C --> D[Execute Startup Logic (e.g., Load Settings, Initialize UI)]
    B -- No --> E[Extension Inactive]
    D --> F[Extension Ready]

Flowchart of Chrome Extension startup event handling.

Implementing Startup Logic in Your Extension

To use the onStartup event, you need to register an event listener in your extension's background script. This script runs in the background and has access to all Chrome Extension APIs. Ensure your manifest.json file correctly specifies a background script.

{
  "manifest_version": 3,
  "name": "My Startup Extension",
  "version": "1.0",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "storage"
  ]
}

Example manifest.json for a Manifest V3 extension with a service worker.

// background.js

chrome.runtime.onStartup.addListener(() => {
  console.log('Chrome Extension started up!');
  // Perform actions here, e.g., load settings, set alarms, update UI
  chrome.storage.local.get('lastSessionData', (result) => {
    if (result.lastSessionData) {
      console.log('Restoring last session data:', result.lastSessionData);
      // Example: Update a badge text or perform other UI updates
      chrome.action.setBadgeText({
        text: 'ON'
      });
      chrome.action.setBadgeBackgroundColor({
        color: '#4688F1'
      });
    } else {
      console.log('No last session data found.');
      chrome.action.setBadgeText({
        text: ''
      });
    }
  });

  // Example: Set an alarm to run a task periodically
  chrome.alarms.create('dailyTask', {
    delayInMinutes: 1,
    periodInMinutes: 1440 // 24 hours
  });
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'dailyTask') {
    console.log('Daily task alarm fired!');
    // Perform daily tasks here
  }
});

console.log('Background script loaded.');

Example background.js demonstrating onStartup event listener and chrome.storage usage.

Testing Your Startup Logic

To effectively test your onStartup event handler, you need to simulate a browser startup. Simply reloading the extension from chrome://extensions will not trigger onStartup. Instead, you should close and reopen your Chrome browser.

1. Load Your Extension

Go to chrome://extensions, enable 'Developer mode', and click 'Load unpacked' to load your extension directory.

2. Inspect Service Worker

Click on 'Service Worker (inactive)' or 'Service Worker (running)' next to your extension to open the developer tools for your background script. Keep this window open to see console logs.

3. Close Chrome

Completely close all Chrome browser windows.

4. Reopen Chrome

Launch Chrome again. Observe the console in your Service Worker's developer tools. You should see the 'Chrome Extension started up!' message and any subsequent logs from your onStartup handler.