chrome扩展程序中的js代码能否检测到它已作为内容脚本执行? [英] Can js code in chrome extension detect that it's executed as content script?
问题描述
我有一个google chrome扩展程序,它在内容脚本和后台进程/弹出窗口之间共享一些代码.是否可以通过某种简单直接的方法来检查此代码是否作为内容脚本执行? (消息传递行为不同).
I have a google chrome extension that shares some code between it's content script and background process / popup. If it some easy and straightforward way for this code to check if it's executed as content script or not? (message passing behavior differs).
我可以在清单中包含其他标记" javascript或调用内容脚本中不可用的某些chrome功能并检查异常-但是这些方法看起来很尴尬.也许这是进行此检查的一些简单明了的方法?
I can include additional "marker" javascript in manifest or call some chrome fnction unavailable from content script and check for exceptions - but these methods looks awkward to be. Maybe it's some easy and clean way to make this check?
推荐答案
检查您的脚本是否以内容脚本,请检查它是否未在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.
这篇关于chrome扩展程序中的js代码能否检测到它已作为内容脚本执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!