How to determine if a script is running as the contents of a script or background script?

In a Chrome extension, a script may be included as the contents of a script or background script. Most of the things he does are one and the same, but some of them will change depending on a different context.

The question is, how does the script determine in what context it is being executed? Thank.

+4
source share
3 answers

Well, I managed to solve this:

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

This is because an exception will be thrown if the contents of the script try to access chrome. * parts except chrome.extension.

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

+3
source

, , ​​ try, chrome , .

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(':','');
        }
    }
};
+3

The best solution I have found for this problem comes from here.

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

Source: https://habr.com/ru/post/1780585/


All Articles