Search code examples
google-chrome-extension

Can js code in chrome extension detect that it's executed as content script?


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).

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?


Solution

  • 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
    }
    

    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 / ...

    (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.)

    Explanation of revised answer

    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 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.

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