且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome 扩展代码 vs 内容脚本 vs 注入脚本

更新时间:2023-12-05 09:00:28

Chrome 扩展程序中的 JavaScript 代码可以分为以下几组:

JavaScript code in Chrome extensions can be divided in the following groups:

内容脚本(通过清单文件或chrome.tabs.executeScript) - 部分访问一些chrome API,具有对页面 DOM 的完全访问权限(访问任何 window 对象,包括框架).
内容脚本在扩展和页面之间的范围内运行.内容脚本的全局 window 对象不同于页面/扩展的全局命名空间.

Content scripts (via the manifest file or chrome.tabs.executeScript) - Partial access to some of the chrome APIs, full access to the page's DOM (not to any of the window objects, including frames).
Content scripts run in a scope between the extension and the page. The global window object of a Content script is distinct from the page/extension's global namespace.

注入的脚本(通过 此方法 在内容脚本中) - 对页面中所有属性的完全访问权限.无法访问任何 chrome.* API.
注入的脚本表现得好像它们被页面本身包含一样,并且没有以任何方式连接到扩展.请参阅这篇文章 以了解有关各种注入方法的更多信息.

Injected scripts (via this method in a Content script) - Full access to all properties in the page. No access to any of the chrome.* APIs.
Injected scripts behave as if they were included by the page itself, and are not connected to the extension in any way. See this post to learn more information on the various injection methods.

要将消息从注入的脚本发送到内容脚本,必须使用事件.有关示例,请参阅此答案.注意:在扩展中从一个上下文传输到另一个上下文的消息是自动 (JSON) 序列化和解析.

To send a message from the injected script to the content script, events have to be used. See this answer for an example. Note: Message transported within an extension from one context to another are automatically (JSON)-serialised and parsed.

在您的情况下,后台页面中的代码 (chrome.tabs.onUpdated) 可能在内容脚本 script.js 被评估之前被调用.所以,你会得到一个 ReferenceError,因为 init 不是 .

In your case, the code in the background page (chrome.tabs.onUpdated) is likely called before the content script script.js is evaluated. So, you'll get a ReferenceError, because init is not .

此外,当您使用 chrome.tabs.onUpdated 时,请确保测试页面是否已完全加载,因为该事件会触发两次:加载前和完成时:

Also, when you use chrome.tabs.onUpdated, make sure that you test whether the page is fully loaded, because the event fires twice: Before load, and on finish:

//background.html
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete') {
        // Execute some script when the page is fully (DOM) ready
        chrome.tabs.executeScript(null, {code:"init();"});
    }
});