Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从chrome扩展中的内容脚本访问全局对象_Javascript_Html_Google Chrome Extension - Fatal编程技术网

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

Javascript 从chrome扩展中的内容脚本访问全局对象,javascript,html,google-chrome-extension,Javascript,Html,Google Chrome Extension,我在.js文件中定义了一个全局对象。例如,file1.js包含全局对象SomeObject。此文件在background.html中加载 由于file1.js包含在background.html中,因此我可以访问此页面中的全局对象。所以这里没有问题 当执行类似单击扩展按钮的事件时,我正在使用chrome.tabs.executeScript(null,{file:“contentscript.js”})运行内容脚本api 在这种情况下,如何访问contentscript中的某个对象?无法从或注入

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

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

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


在这种情况下,如何访问contentscript中的某个对象?

无法从或注入脚本直接访问背景页的全局对象

要从注入的脚本中使用背景页的方法,请执行以下步骤:

  • 内容脚本:将事件侦听器绑定到页面。
    每当您想从后台页面通知该方法时:
  • 注入脚本:创建并触发此特定事件。
    → 将触发1)中的事件侦听器
  • 在此事件侦听器中,用于从后台请求功能
  • 在后台页面中,使用处理此请求
  • (可选)使用在原始选项卡中插入代码
  • 要从内容脚本中使用背景页的方法,只需要步骤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'
            });
        }
    });
    
    另见
    • 所以:你应该知道什么
    • 所以:示例代码:

    是否有任何方法可以在不以任何方式修改内容脚本的情况下执行此操作?错误。请注意,sendMessage的参数数与addListener的参数数不同。在使代码正常工作后,我得到了:chrome.runtime.sendMessage(chrome.runtime.id,arg,sender_id,cb);