如何从Chrome扩展程序中的内容脚本中获取变量?

时间:2016-04-26 20:04:09

标签: javascript google-chrome variables google-chrome-extension

我试图修改Google sample code以进行代码注入。文件manifest.json包含后台脚本:

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

我添加了content script

  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["filter.js"]
    }
  ],

现在,当用户点击扩展程序按钮时,我想调用foo()中定义的功能filter.js。我在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

我知道我错误地引用了变量,但是如何做到这一点?

1 个答案:

答案 0 :(得分:1)

请看一下sendMessageonMessage,这些示例会改编自Google:

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"});
        }
});
相关问题