Send a message from content script:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
Send a message from an extension to content script:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
On the receiving end, you need to set up an runtime.onMessage event listener to handle the message. This looks the same from a content script or extension page.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
APIs
- Fired when a message is sent from either an extension process or a content script.
- Sends a single message to event listeners within your
extensionor a differentextension.
If sending to your extension, theruntime.onMessageevent will be fired in each page.
Note thatextensionscannot send messages tocontent scriptsusing this method. To send messages tocontent scripts, usetabs.sendMessage.
chrome.runtime.onMessage.addListener(function callback)
chrome.runtime.sendMessage(string extensionId, any message, object options, function responseCallback)
本文介绍了如何在Chrome扩展程序中使用chrome.runtime.sendMessage及chrome.runtime.onMessage进行消息传递。具体包括从内容脚本发送消息到扩展程序背景页,以及从扩展程序发送消息到内容脚本的方法,并展示了如何设置监听器来处理这些消息。
7140

被折叠的 条评论
为什么被折叠?



