且构网

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

chrome扩展程序中的js代码能否检测到它已作为内容脚本执行?

更新时间:2023-12-05 18:37:34

检查您的脚本是否以内容脚本,请检查它是否未在chrome-extension方案上执行.

To check whether or not your script is running as a content script, check if it is not being executed on a chrome-extension scheme.

if (location.protocol == 'chrome-extension:') {
    // Running in the extension's process
    // Background-specific code (actually, it could also be a popup/options page)
} else {
    // Content script code
}

如果您进一步想知道自己是否在后台页面中运行,请使用 chrome.extension.getBackgroundPage() === window.如果为真,则代码在后台运行.如果没有,则说明您是在弹出式窗口/选项页/...的上下文中运行.

If you further want to know if you're running in a background page, use chrome.extension.getBackgroundPage()=== window. If it's true, the code is running in the background. If not, you're running in the context of a popup / options page / ...

(如果要检测代码是否在扩展程序的上下文中运行,即不在常规网页的上下文中运行,请检查chrome.extension是否存在.)

(If you want to detect if the code is running in the context of an extension, ie not in the context of a regular web page, check if chrome.extension exists.)

以前,我的回答建议检查是否定义了特定于背景的API,例如 chrome.tabs .从Chrome 27/Opera 15开始,此方法会带来不良的副作用:即使您不使用该方法,也会在控制台中记录以下错误(每个API每个页面加载最多一次):

Previously, my answer suggested to check whether background-specific APIs such as chrome.tabs were defined. Since Chrome 27 / Opera 15, this approach comes with an unwanted side-effect: Even if you don't use the method, the following error is logged to the console (at most once per page load per API):

chrome.tabs不可用:您无权访问此API.确保所需的权限或清单属性包含在manifest.json中.

chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.

这不会影响您的代码(!!chrome.tabs仍为false),但是用户(开发人员)可能会感到烦恼,并卸载您的扩展程序.

This doesn't affect your code (!!chrome.tabs will still be false), but users (developers) may get annoyed, and uninstall your extension.