检测代码是否作为Chrome扩展程序运行
我正在处理一些需要作为网页运行的代码,并且如果它以 Chrome扩展,我希望能够做更多的事情。我使用的是:
I am working with some code that needs to be run as a page, and if it's being run as a Chrome Extension, I want to be able to do additional things. What I'm using is:
<script>
if (chrome && chrome.extension) {
// extension stuff
}
</script>
这似乎是一个很好的功能 检测。使用用户代理字符串会导致我麻烦,因为无论上下文(网页还是扩展名)都是一样的。
This seems like a good capability detection. Using user agent string causes me trouble because it's the same no matter the context (web page vs. extension).
问题:还有其他更可靠的技术用于检测一段代码在Chrome扩展中运行?
Question: are there other more reliable techniques for detecting if a piece of code is running inside a Chrome extension?
更新:我想知道是否有一些内容可以放入我的 manifest.json
文件,然后我就可以回过头再读。请注意,我正在处理的扩展并不是一直运行的持久性事物,它是一个运行在单个窗口或浏览器选项卡中的内容应用程序,无需与其他窗口或选项卡或其他任何内容交互。
Update: I'm wondering if there's something I can put into my manifest.json
file that I can then read back. Note, that the extension I'm working on is not intended as a persistent thing that runs all the time, it's a content application that runs in a single window or browser tab and has no need to interact with other windows or tabs or anything else.
这里有很多复杂的答案,您可以通过检查是否存在,轻松检测您是否在Chrome扩展中运行和 chrome.runtime.id
:
So many complicated answers here, while you can easily detect whether you're running in a Chrome extension by checking for existence and non-emptiness of chrome.runtime.id
:
if (window.chrome && chrome.runtime && chrome.runtime.id) {
// Code running in a Chrome extension (content script, background page, etc.)
}