Chrome plug-in development: Service Worker, Content Scripts, and plug-in internal web page workflow

Chrome plug-in development: Service Worker, Content Scripts and plug-in internal web page workflow

The core components of the Chrome plug-in include Service Worker, Content Scripts, and the plug-in internal web page (Popup), each of which has different workflows and functions. This article details the collaboration between these components and their purpose.

1. Service Worker

Service Worker is the background script of the Chrome plug-in. Its main task is to intercept and process network requests, and manage cache. The following is the workflow of Service Worker:

  • Installation: Service Worker triggers the installation event when it registers for the first time. In this event, the required resources are typically cached so they are accessible when offline. This step is critical for providing offline support.

  • Activation: The activation event is triggered after the Service Worker is installed. At this stage, cleanup operations are typically performed, such as deleting caches of older versions. This ensures that new versions of the Service Worker can take over smoothly, while also helping to clean up caches that are no longer needed.

  • After activation (Active): Service Worker remains active after activation and can intercept requests and perform background tasks, such as background data synchronization and push notifications. Its active state allows it to respond quickly to events, improving the plug-in’s performance.

  • Termination: If the Service Worker is inactive for a long time, the browser may terminate it to release resources. However, it is important to note that even during sleep, the Service Worker can still receive and process messages, but will not perform heavyweight tasks to avoid affecting performance.

Service Worker is usually used to implement functions such as offline support, performance improvement and background data synchronization. Service Worker is a script that runs stably in the background. Some time-consuming operations are generally placed in Service Worker for offline processing. Service Worker can also be used as a message transfer station

As a background script, Service Worker does not have a browser environment and cannot use window objects. It only has chrome objects. In the service worker, you can use a timer to wake up the service worker regularly to ensure that it is always running in the background. Of course, it will consume more user time. resource

2. Content Scripts

Content Scripts are scripts that can be embedded into browsing pages, and their main task is to interact with the page. The following is the workflow of Content Scripts:

  • Injection: Content Scripts are injected into the page when the browser loads the page, and can access the DOM and JavaScript environment of the page. This enables them to interact with page content.

  • Execution: They can modify the content and style of the page, respond to user interaction events, and communicate with the JavaScript code on the page. This enables them to add additional functionality or modify the appearance and behavior of the page.

  • Termination: When the page is unloaded or closed, Content Scripts will be destroyed to release resources.

Content Scripts are usually used to add additional functionality to web pages, modify the appearance and behavior of the page, and interact with the JavaScript code of the page. However, Content Scripts cannot access the JavaScript code of the page and can only access and modify the DOM elements on the page. It is equivalent to referencing a piece of script code on the page. If the injected page is also controlled by you, you can communicate with the plug-in through some means, such as postmessage, etc.

Content Scripts are injected and run in the browser page. They can share the window object with the browser page and can also use some chrome object APIs.

3. Plug-in internal web page (Popup)

The internal web page of the plug-in, usually a pop-up page (Popup), is used to display the plug-in’s settings, options or interactive interface with the user. The following is the workflow of Popup:

  • Creation: Popup is created and displayed when the user clicks on the plug-in icon. It is usually used to configure the settings of the plug-in. This is the primary interface for direct interaction with the user.

  • Interaction: Users can interact with the plug-in on the Popup page, perform operations or modify settings. This allows Popup to be used to perform tasks related to the plugin’s functionality.

  • Termination: When the user closes the Popup, it will be destroyed to release resources.

Popups are typically used to provide a user-friendly interface, configure plugin settings, and perform tasks related to plugin functionality.

Popup usually cannot be checked in or closed by the developer. Popup will be automatically created only when the user clicks on the extension program Popup in the toolbar. After the user clicks elsewhere, Popup will be automatically destroyed.

Communication methods

Communication between different components usually needs to be implemented through Service Worker scripts as an intermediary. The following is an example of communication:

Send message to Content Scripts:

  1. Use chrome.tabs.query in a Service Worker script to find the tab that is running Content Scripts and send a message to it.

  2. Content Scripts need to listen to and respond to these messages through chrome.runtime.onMessage.

Send messages to Content Scripts in Service Worker scripts:

// Query matching tabs
chrome.tabs.query({<!-- --> active: true, currentWindow: true }, function(tabs) {<!-- -->
  //Send message to Content Scripts
  chrome.tabs.sendMessage(tabs[0].id, {<!-- --> from: 'Service Worker', message: 'Hello from Service Worker' });
});

Listening for messages in Content Scripts:

//Listen to messages from Service Worker in Content Scripts
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {<!-- -->
  if (message.from === 'Service Worker') {<!-- -->
    console.log('Received message in Content Script:', message.message);
    //Perform the corresponding operation
  }
});

This method sends the message to Content Scripts through the background script, ensuring that the message can be correctly delivered to Content Scripts.

Send a message to Popup:

  1. The Popup page can use chrome.runtime.sendMessage to send messages to the background script.

  2. The Service Worker script can forward the received message to the Popup page.

  3. The Popup page needs to listen to and respond to these messages through chrome.runtime.onMessage.

Background sends a message to Popup:

//Send a message to the popup page in the Service Worker script
chrome.runtime.sendMessage({<!-- -->from: 'Service Worker',message: "Hello from Service Worker!"});

Content Scripts send message to Popup:
Since content and popup run in different environments, they need to use background for message forwarding.
content sends message to background

// content Send message to Service Worker
chrome.runtime.sendMessage({<!-- -->from:'content', to:'popup', message:'Hello from content!'}, function (response) {<!- - -->
    console.log('Reply message received:', response)
  });

Service Worker accepts messages and forwards them to popup

//Receive the message in the Service Worker script and forward it to the Popup page
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {<!-- -->
  if (message.from === 'content' & amp; & amp; message.to === 'popup') {<!-- -->
    //Forward the message to the Popup page
    chrome.runtime.sendMessage(message, function (response) {<!-- --> // Registered a callback function to obtain the information returned by the message receiver
   console.log('Reply message received:', response)
   sendResponse(response)
  });
  }
});

Listen to messages in the Popup page:

//Listen to messages from Service Worker in the Popup page
chrome.runtime.onMessage.addListener(function(message

, sender, sendResponse) {<!-- -->
  if (message.from === 'content' & amp; & amp; message.to === 'popup') {<!-- -->
    console.log('Received message in Popup:', message.message);
    //Perform the corresponding operation
    const response = 'nothing'
    sendResponse(response)
  }
});

The messaging API supports asynchronous mode and returns a promise, but if asynchronous messaging is used, the callback function cannot be triggered correctly (sendResponse: After receiving the message, the message receiver can use sendResponse to send the processed result to the message sender)

It should be noted that popup and content depend on user behavior. The user can choose to close the page, and the message window will be closed at this time.