从chrome扩展中的内容脚本访问全局对象

Viv*_*R K 6 html javascript google-chrome-extension

我在.js文件中定义了一个全局对象.例如,file1.js包含全局对象SomeObject.此文件在background.html中加载.

由于file1.js包含在background.html中,因此我可以访问此页面中的全局对象.所以这里没有问题.

当执行诸如单击扩展按钮之类的事件时,我正在使用chrome.tabs.executeScript(null, {file: "contentscript.js"});api 运行内容脚本.

在这种情况下,如何访问脚本中的SomeObject?

Rob*_*b W 20

没有办法让直接访问从一到后台网页的全局对象的内容脚本注入脚本.

要从注入的脚本中使用背景页面的方法,请按照下列步骤操作:

  1. 内容脚本:将事件监听器绑定到页面示例1.
    每当您想从后台页面通知方法时:
  2. 注入脚本:创建并触发此特定事件示例1.
    →来自1)的事件监听器被触发.
  3. 在此事件侦听器中,用于chrome.runtime.sendMessage从后台示例2请求功能.
  4. 在后台页面中,使用处理此请求chrome.runtime.onMessage.
  5. (可选)使用在原始选项卡中注入代码chrome.tabs.executeScript(tab.id, func).

要从内容脚本使用背景页面的方法,只需要步骤3和4.
这是一个示例,其中内容脚本与后台页面通信:

// Example background page
function some_method(arg_name) {
    return localStorage.getItem(arg_name);
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.type == 'localStorage - step 4') {
        callback( some_method(request.name) );
    } else if (request.type == 'localStorage - step 5') {
        localStorage.setItem(request.name, request.value);
    }
});

// Example contentscript.js
chrome.runtime.sendMessage({
    type: 'localStorage - step 4',
    name: 'preference'
}, function(value) {
    if (value === null) {
        // Example: If no preference is set, set one:
        chrome.runtime.sendMessage({
            type: 'localStorage - step 5',
            name: 'preference',
            value: 'default'
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

也可以看看