chrome.runtime.onMessage
时间: 2024-04-04 17:11:15 浏览: 137
chrome.runtime.onMessage is an event listener function in the Chrome Extension API. It is used to listen for messages sent from other parts of the extension, such as content scripts or background scripts.
Syntax:
chrome.runtime.onMessage.addListener(callback)
The "callback" parameter is a function that will be called when a message is received. The function takes three arguments:
- message: the message that was sent
- sender: information about the sender of the message, including their identity (extension ID or URL) and the context they are in (tab or frame)
- sendResponse: a function that can be used to send a response back to the sender
Example Usage:
```
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.type === "greeting") {
console.log("Received greeting from " + sender.url);
sendResponse({type: "response", content: "Hello from the extension!"});
} else {
console.log("Received unknown message type: " + message.type);
}
});
```
In this example, the extension is listening for messages of type "greeting". If it receives one, it logs a message to the console and sends a response back to the sender. If it receives a message of any other type, it logs an error message.
阅读全文