三种脚本
弹出页脚本:popup
后台脚本:backgroup
内容脚本:contentscript
短连接
popup <-> background
popup可以直接调用background中的JS方法,也可以直接访问background的DOM
// background.js
function test()
{
alert('我是background!');
}
// popup.js
var bg = chrome.extension.getBackgroundPage();
bg.test(); // 访问bg的函数
alert(bg.document.body.innerHTML); // 访问bg的DOM
background访问popup如下(前提是popup已经打开)
var views = chrome.extension.getViews({type:'popup'});
if(views.length > 0) {
console.log(views[0].location.href);
}
popup/background -> contentscript
popup/background 发送
function sendMessageToContentScript(message, callback)
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
chrome.tabs.sendMessage(tabs[0].id, message, function(response)
{
if(callback) callback(response);
});
});
}
sendMessageToContentScript(
{cmd:'test', value:'你好,我是popup!'},
function(response)
{
console.log('来自content的回复:'+response);
}
);
contentscript 接收
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
// console.log(sender.tab ?"from a content script:" + sender.tab.url :"from the extension");
if(request.cmd == 'test') alert(request.value);
sendResponse('我收到了你的消息!');
});
contentscript-> popup/background
contentscript 发送
chrome.runtime.sendMessage(
{greeting: '你好,我是content-script呀,我主动发消息给后台!'},
function(response) {
console.log('收到来自后台的回复:' + response);
}
);
popup/background 接收
// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
console.log('收到来自content-script的消息:');
console.log(request, sender, sendResponse);
sendResponse('我是后台,我已收到你的消息:' + JSON.stringify(request));
});
长连接
// popup.js:
getCurrentTabId((tabId) => {
var port = chrome.tabs.connect(tabId, {name: 'test-connect'});
port.postMessage({question: '你是谁啊?'});
port.onMessage.addListener(
function(msg) {
alert('收到消息:'+msg.answer);
if(msg.answer && msg.answer.startsWith('我是'))
{
port.postMessage({question: '哦,原来是你啊!'});
}
}
);
}
);
// content-script.js:
// 监听长连接
chrome.runtime.onConnect.addListener(function(port) {
console.log(port);
if(port.name == 'test-connect') {
port.onMessage.addListener(function(msg) {
console.log('收到长连接消息:', msg);
if(msg.question == '你是谁啊?')
port.postMessage({answer: '我是你爸!'});
});
}
});