background.js
Overview
The background.js file serves as the background script for a Chrome extension. Its primary purpose is to listen for key extension lifecycle events and inter-script messages, handle these events, and coordinate data storage within the extension's local storage. Specifically, it:
Detects when the extension is installed and logs a confirmation message.
Listens for messages from content scripts, particularly those carrying page information.
Saves received page information into Chrome's local storage.
Sends acknowledgment responses back to the message sender.
This file acts as a central event handler and data manager that supports communication and persistence for the extension's functionality.
Detailed Explanation
Event Listeners
1. chrome.runtime.onInstalled.addListener(callback)
Purpose:
Registers a listener that triggers when the extension is installed or updated.Parameters:
callback: A function executed when the event occurs. It takes no parameters.
Behavior:
Logs the message"Tiện ích đã được cài đặt!"(Vietnamese for "The extension has been installed!") to the console, indicating successful installation.Usage Example:
chrome.runtime.onInstalled.addListener(() => { console.log("Tiện ích đã được cài đặt!"); });
2. chrome.runtime.onMessage.addListener(callback)
Purpose:
Listens for messages sent from other parts of the extension (e.g., content scripts).Parameters:
message: The object sent by the sender, expected to contain at least anactionproperty.sender: An object containing information about the message sender.sendResponse: A function to send a response back to the sender.
Behavior:
When a message has anactionproperty equal to"PAGE_INFO":Logs the entire message object to the console.
Saves the message object to Chrome's local storage under the key
pageInfo.Logs confirmation of saving to the console.
Sends a success response back to the sender.
Return value:
None explicitly returned, but must callsendResponseto asynchronously reply.Usage Example:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === "PAGE_INFO") { console.log(message); chrome.storage.local.set({ pageInfo: message }, () => { console.log("Page info saved to local storage."); }); sendResponse({ status: "success", message: "Page info received and processed." }); } });
Implementation Details and Algorithms
The file uses Chrome Extensions API event listeners to respond to extension lifecycle and messaging events.
It employs asynchronous storage via
chrome.storage.local.setto persist data. This API is non-blocking and uses a callback to signal completion.The message handling logic is simple and synchronous in control flow. It only reacts to messages with a specific
actionvalue ("PAGE_INFO"), ensuring robustness against unexpected messages.The response mechanism (
sendResponse) allows for two-way communication between background and content scripts, facilitating confirmation of operations.
Interaction with Other Parts of the System
Content Scripts:
Content scripts likely collect or generate page information and send it viachrome.runtime.sendMessagewith theaction: "PAGE_INFO"payload. The background script listens and stores this information.Storage:
The background script saves received page information in the extension's local storage (chrome.storage.local), making it accessible for future retrieval by other extension components, such as popup scripts or options pages.Extension Lifecycle:
The installation listener can be extended to handle initialization tasks or migrations when the extension is updated or first installed.
Visual Diagram
Below is a flowchart illustrating the main functional flow of background.js:
flowchart TD
A[Extension Installed] --> B[Log "Tiện ích đã được cài đặt!"]
C[Message Received] --> D{Is message.action === "PAGE_INFO"?}
D -- Yes --> E[Log message content]
E --> F[Save message to chrome.storage.local as 'pageInfo']
F --> G[Log "Page info saved to local storage."]
G --> H[Send response: {status: "success", message: "..."}]
D -- No --> I[Ignore message]
style A fill:#f9f,stroke:#333,stroke-width:1px
style C fill:#bbf,stroke:#333,stroke-width:1px
style D fill:#ffc,stroke:#333,stroke-width:1px
style F fill:#cfc,stroke:#333,stroke-width:1px
Summary
background.jsis a core communication and storage handler in the Chrome extension.It listens for installation events and logs a message.
It listens for messages from content scripts with page information.
It saves received page information in local storage for persistent access.
It sends confirmation responses to message senders.
The file is key for coordinating data flow and extension lifecycle awareness.
This design provides a simple yet effective mechanism for data collection, storage, and inter-script communication within the extension.