我有一个谷歌浏览器扩展,它在它的内容脚本和后台进程/弹出窗口之间共享一些代码。如果此代码有一些简单直接的方法来检查它是否作为内容脚本执行?(消息传递行为不同)。
我可以在清单中包含额外的“标记”javascript,或者调用内容脚本中不可用的一些 chrome 函数并检查异常 - 但这些方法看起来很尴尬。也许这是进行此检查的一些简单而干净的方法?
我有一个谷歌浏览器扩展,它在它的内容脚本和后台进程/弹出窗口之间共享一些代码。如果此代码有一些简单直接的方法来检查它是否作为内容脚本执行?(消息传递行为不同)。
我可以在清单中包含额外的“标记”javascript,或者调用内容脚本中不可用的一些 chrome 函数并检查异常 - 但这些方法看起来很尴尬。也许这是进行此检查的一些简单而干净的方法?
要检查您的脚本是否作为内容脚本运行,请检查它是否没有在chrome-extension方案上执行。
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
(如果您想检测代码是否在扩展的上下文中运行,即不在常规网页的上下文中,请检查是否chrome.extension存在。)
以前,我的回答建议检查是否定义了特定于背景的 API chrome.tabs。从 Chrome 27 / Opera 15 开始,这种方法带来了一个不需要的副作用:即使您不使用该方法,控制台也会记录以下错误(每个 API 每个页面加载最多一次):
chrome.tabs 不可用:您无权访问此 API。确保您的 manifest.json 中包含所需的权限或清单属性。
这不会影响您的代码(!!chrome.tabs仍然会false),但用户(开发人员)可能会感到恼火,并卸载您的扩展程序。
The function chrome.extension.getBackgroundPage is not defined at all in content scripts, so alone it can be used to detect whether the code is running in a content script:
if (chrome.extension.getBackgroundPage) {
// background page, options page, popup, etc
} else {
// content script
}
There are more robust ways to detect each context separately in a module I wrote
function runningScript() {
// This function will return the currently running script of a Chrome extension
if (location.protocol == 'chrome-extension:') {
if (location.pathname == "/_generated_background_page.html")
return "background";
else
return location.pathname; // Will return "/popup.html" if that is the name of your popup
}
else
return "content";
}