Ryan Li
Ryan Li

Reputation: 9340

How to tell if a script is run as content script or background script?

In a Chrome extension, a script may be included as a content script or background script. Most stuff it does is the same, but there are some would vary according to different context.

The question is, how could a script tell which context it is being run at? Thank you.

Upvotes: 4

Views: 1987

Answers (4)

Axtru
Axtru

Reputation: 191

The background service worker at Manifest v3 does not contain a window.

I use this as part of my extension error handling which reloads the content scripts, when i receive an Extension context invalidated error:

...

if (!self.window) {
  console.warn('Background error: \n', error);
} else {
  location.reload();
}

...

Upvotes: 1

Jack Steam
Jack Steam

Reputation: 5289

The best solution I've found to this problem comes from over here.

const isBackground = () => location.protocol === 'chrome-extension:'

Upvotes: 4

jdavid.net
jdavid.net

Reputation: 751

I think this is a fairly robust version that worked in my initial tests and does not require a slower try catch, and it identifies at least the three primary contexts of a chrome extension, and should let you know if you are on the base page as well.

av = {};
av.Env = {
    isChromeExt: function(){
        return !!(window['chrome'] && window['chrome']['extension'])
    },
    getContext: function(){
        var loc = window.location.href;
        if(!!(window['chrome'] && window['chrome']['extension'])){
            if(/^chrome/.test(loc)){
                if(window == chrome.extension.getBackgroundPage()){
                    return 'background';
                }else{
                    return 'extension';
                }
            }else if( /^https?/.test(loc) ){
                return 'content';
            }
        }else{
            return window.location.protocol.replace(':','');
        }
    }
};

Upvotes: 5

Ryan Li
Ryan Li

Reputation: 9340

Well I managed to work out this:

var scriptContext = function() {
    try {
        if (chrome.bookmarks) {
            return "background";
        }
        else {
            return "content";
        }
    }
    catch (e) {
        return "content";
    }
}

It's because an exception would be thrown if the content script tries to access the chrome.* parts except chrome.extension.

Reference: http://code.google.com/chrome/extensions/content_scripts.html

Upvotes: 2

Related Questions