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).
Question: are there other more reliable techniques for detecting if a piece of code is running inside a Chrome extension?
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.
Advertisement
Answer
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.) }