Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 734
Ryan Li Avatar asked Feb 25 '23 14:02

Ryan Li


1 Answers

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(':','');
        }
    }
};
like image 98
jdavid.net Avatar answered May 24 '23 03:05

jdavid.net