how do i toggle on/off content_scripts in a google extension?

后端 未结 2 716
栀梦
栀梦 2021-02-10 10:39

I have this simple extension, it displays icon on chrome\'s toolbar and shows a enable/disable button. i want to add function to the button to disable or enable the conten

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 11:14

    After some research i figured out how to solve this by using backround pages, sendMessage and localstorage.

    background pages work as a communicator between popup.js and content_scripts.js, they are on two different documents and it's not possible to pass variables between them directly.

    To enable background page in mamifest i added:

    "background": {
    "scripts": ["background.js"],
    "persistent": true
    },
    

    localstorage save variables locally and remember them even when the browser is closed and opened again, so when enable/disable button is clicked it set localStorage['status'] = 1/0 which can be accessed through background.js and passed to content_scripts.js.

    To set localStorage variable i added to popup.js:

    if(!localStorage.status) localStorage['status'] = 1;
    toggle(2);
    enable.onclick = function(){toggle(0)};
    disable.onclick = function(){toggle(1)};
    function toggle(n){
        if((n == 0) && (enable.parentNode == list)){
            list.removeChild(enable);
            list.appendChild(disable);
            localStorage.status = 1;
        }else if((n == 1) && (disable.parentNode == list)){
            list.removeChild(disable);
            list.appendChild(enable);
            localStorage.status = 0;
        }else if((n == 2) && (!list.hasChildNodes())){
            list.appendChild((localStorage.status == 1) ? disable : enable);
            chrome.browserAction.setIcon({path: (localStorage.status == 1) ? "icons/icon19.png" : "icons/icon19_disabled.png"});
        }else{
            return;
        }
    }
    

    To pass localStorage.status to content_scripts.js i had to use sendMessage on content_scrips.js which on loaded send request message to background.js, and onMessage on background.js which listens to requests and send response to content_scripts.js with the localStorage.status value.

    background.js:

    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.type == "status") sendResponse({status: localStorage.status});
    });
    

    content_scripts.js

    var fn = function(){...};
    chrome.runtime.sendMessage({type: "status"}, function(response) {
        if(response.status == 1) fn();
        return;
    });
    

    That's it, hope someone find it useful.

提交回复
热议问题