Disable / enable Chrome extension through browser action / icon

The chrome extension I am developing embeds content scripts and css on every page of a website. However, the user may have a specific page or pages on which he or she does not want the extension to work, so it would be great if I could configure the browser action as basically turning on / off.

What I would like to do is something like this:

chrome.browserAction.onClicked.addListener(function(tab) { //IF ENABLED THEN DISABLE //IF DISABLED THEN ENABLE } 

Any help would be greatly appreciated!

+7
source share
2 answers

Such an API is not provided. But there are two possible workarounds:

I. You can use the flag variable "disabled" and update it from your background page.

Background page:

 function disableExtension(disabled) { chrome.windows.getAll({populate : true}, function (window_list) { for (var i = 0; i < window_list.length; ++i) { var window = window_list[i]; for (var j = 0; j < window.tabs.length; ++j) { var tab = window.tabs[j]; if (checkContentScriptExists(tab)) { chrome.tabs.executeScript(tab.id, {code : "disabled = " + disabled + ";"}, allTabs: true) } } } // No matching url found. Open it in the new tab chrome.tabs.create({ url : url, selected: true }); }); } 

A content script should check the status before running

 if (!disabled) doSomething(); 

II. Controversial Approach to Keeping a Disable Variable in the Background Content of Age

Background page:

 function disableExtension(disabled) { global.disabled = disabled; } chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.msg == "getDisabled") { sendResponse({disabled: global.disabled}); return true; } }); 

and the content script should request the current disabled status before executing

 chrome.runtime.sendMessage({msg: "getDisabled"}, function(response) { if (!response.disabled) doSomething(); }); 
+5
source

Chrome extensions have their own APIs. You can call them through content scripts. Not sure if you can call them through third-party JS. Refer to this ink

Hope this helps.

0
source

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


All Articles