Chrome的消息傳遞,能夠在Web(經過content script)和擴展之間進行,任意一方均可發送或接收消息。Web(經過content script)發送消息以下:chrome
chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); });
經過chrome.runtime.sendMessage函數發送消息,其中{greeting: "hello"}是消息對象(大括號的用法見參考資料[2]);function(response) {...}是回調函數,處理接收方發回的消息。函數
插件發送消息須要肯定接收的Tab,以下:url
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) { console.log(response.farewell); }); });
以上代碼指定當前tab爲消息的接收者。插件
接受端須要經過runtime.onMessage事件處理消息:code
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"}); });
事件處理經過function(request, sender, sendResponse){...}完成,以上代碼處理消息時在控制檯記錄發送者的消息,回覆「goodbye」消息。對象