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

Accessing global object from content script in chrome extension

本文关键字:脚本 访问 全局 对象 chrome 扩展 程序      更新时间:2023-09-26

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

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

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

在这种情况下,我如何访问内容脚本中的某个对象?

无法从内容脚本或注入的脚本直接访问后台页面的全局对象。

要使用注入脚本中的后台页面方法,请执行以下步骤:

  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'
        });
    }
});

参见

  • SO:您应该了解的有关后台脚本、内容脚本与注入脚本的信息。
  • SO:示例代码:在注入的脚本和内容脚本之间进行通信。