如何从Chrome扩展中的内容脚本获取变量?
问题描述:
我正在尝试修改Google的代码注入sample code。文件manifest.json
包括后台脚本:如何从Chrome扩展中的内容脚本获取变量?
"background": {
"scripts": ["background.js"],
"persistent": false
},
,我添加content script:
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["filter.js"]
}
],
现在我想,当用户点击扩展的按钮呼叫filter.js
定义功能foo()
。我这样做在background.js
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: 'foo(testText);'
});
});
其中foo()
在filter.js
定义为
function foo(test) {
alert('Test: ' + String(test));
}
var testText = 'foo';
我可以执行的功能,但无法通过testText
变量。我得到VM3181:1 Uncaught ReferenceError: testText is not defined
。
我知道我指的是变量不正确,但如何做到这一点对吗?
答
看看sendMessage
和onMessage
,从实例谷歌改变用途:
在background.js
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "foo"}, function(response) {
console.log(response.farewell);
});
});
而且在filter.js
:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "foo") {
//your Foo function can be called
sendResponse({farewell: "bar"});
}
});