Search code examples
javascriptfirefox-addonfirefox-addon-webextensions

Disabling / enabling javascript only in one tab from the Firefox/Chrome extension (using Web Extensions)


I'm making an extension (add on) for Firefox/Chrome/Opera/etc using Web Extensions system.

I want to enable or disable javascript, but per tab, not globally. I.e. in first tab it would be disabled, but in a second one - enabled.

I'm trying to find a solution here, but I can't see it:

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs

Or maybe, there is a way to do that with just pure Javascript? BTW - that is why I also tagged this with Javascript.


Solution

  • You can do this using the chrome.contentsettings API. You will need to declare "contentsettings" permission in your manifest.json:

    "permissions": [   
       "contentSettings"
     ]
    

    Then, to allow/disallow Javascript:

    this.setJavascript=function(setting){
    
        if(!(['allow','block'].includes(setting)) ){
            console.log("invalid setting passed to setjavascript");
            setting='allow';
        }
    
        //  *://www.example.com/*
        var pattern= "*://"+this.domain+"/*";
        chrome.contentSettings.javascript.set({
                'primaryPattern': pattern,
                'setting': setting,
            }, function () {
               // console.log("Javascript blocked");
            }
        );
    }