background.js 代码如下:
/* global chrome */
'use strict'
console.log('content-script.js')
var btn = document.createElement('button')
btn.id = 'send_to_background'
btn.innerText = 'send_to_background'
btn.style.position = 'fixed'
btn.style.zIndex = 999999
btn.style.top = '100px'
btn.style.left = '100px'
btn.onclick = function () {
// 向 background 发消息
chrome.runtime.sendMessage({greeting: "hello Background"}, function(response) {
console.log(response.farewell);
});
}
document.body.insertBefore(btn, document.body.firstChild)
// 接收来自 background 或 popup 的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// console.log(sender.tab ? "From a content script:" + sender.tab.url : "From the background");
// debugger
console.log(request.greeting)
// 注:接收到消息必须回应,即调用一下sendResponse, 否则会报错 The message port closed before a response was received.
if (typeof sendResponse === 'function') sendResponse({farewell: "I am from content-script" + Math.random()});
});
conten-script.js 代码如下:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
console.log(request.greeting)
// 注:接收到消息必须回应,即调用一下sendResponse, 否则会报错 The message port closed before a response was received.
if (typeof sendResponse === 'function') sendResponse({
farewell: "I am from Background."
});
window.setTimeout(function(){
doit()
}, 2000)
});
function doit() {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
var tabId = tabs.length ? tabs[0].id : null
if (tabId) {
console.log('Background: Send message to Tabs')
chrome.tabs.sendMessage(tabId, {
greeting: "Hello tab " + tabId + ':' + Math.random()
}, function(response) {
console.log('Response from tab ' + tabId + ':' + Math.random())
console.log(response.farewell)
})
}
})
}