在我的Google Chrome扩展程序中,我有一个content_script,我想与我的background_page进行通信。有谁知道如何做到这一点?
我已经找到了一些教程,讨论了后台页面如何与content_script进行通信,但正如我所说,我需要相反的事情发生。
我想运行一个自动脚本来每24小时清除一次缓存。我无法从content_script执行此操作,我必须从后台页面执行此操作。我现在能够让它工作的唯一方法是,如果我按下“按钮”,但正如我之前所说,我希望它每24小时自动运行一次。
BTW-我已经知道Content Scripts不能: 使用chrome。* API(chrome.extension的部分除外) 使用其扩展页面定义的变量或函数 使用由网页或其他内容脚本定义的变量或函数
正如您所看到的那样,第一个项目是:chrome API,但我需要在我的content_script中使用chrome API,所以希望有人可以解决这个问题。请告诉我。
答案 0 :(得分:3)
Message Passing Doc from Google
内容脚本:
chrome.extension.sendRequest({greeting: "hello"}, function(response) { //request
console.log(response.farewell); //receive response
});
背景页面
chrome.extension.onRequest.addListener( //listen to requests
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"}); //send response
});
此外,您可以打开内容脚本和背景页面之间的长期连接:
http://code.google.com/chrome/extensions/messaging.html#connect
contentscript.js
================
var port = chrome.extension.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
if (msg.question == "Who's there?")
port.postMessage({answer: "Madame"});
else if (msg.question == "Madame who?")
port.postMessage({answer: "Madame... Bovary"});
});
background.html
===============
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
if (msg.joke == "Knock knock")
port.postMessage({question: "Who's there?"});
else if (msg.answer == "Madame")
port.postMessage({question: "Madame who?"});
else if (msg.answer == "Madame... Bovary")
port.postMessage({question: "I don't get it."});
});
});