最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding a Disable Button to Chrome Extension - Stack Overflow

programmeradmin4浏览0评论

I am looking to add a disable button in the popup window of my chrome extension that will have it pause functionality like the Adblock extension does. This would remain paused in all tabs until the button is clicked to re-enable it. I have the following code in place, however, the button and functionality don't currently work.

Popup.js file:

function disableButton() {
    var disableButton = document.getElementById("disableButton");
    var isExtensionOn = true;
    if (disableButton.innerHTML == "Disable") {
        isExtensionOn = false;
    } else if (disableButton.innerHTML == "Enable") {
        isExtensionOn = true;
    } else {
        alert("Error");
    }
}

document.addEventListener('DOMContentLoaded', function () {
    var singleButton = document.getElementById("singleButton");
    var br1 = document.getElementById("br1");
    var br2 = document.getElementById("br2");
    //Sends message to event.js (background script) telling it to disable the
    chrome.extension.sendMessage({ cmd: "setOnOffState", data: {value: isExtensionOn} });

    chrome.extension.sendMessage({ cmd: "getOnOffState"}, function(response){
        console.log(response);
        if (response == true){
            disableButton.innerHTML = "Disable";
            disableButton.className = "button button3"
            disableButton.style.display = "";
            br1.style.display = "";
            br2.style.display = "";
        }
        if (response == false){
            disableButton.innerHTML = "Enable";
            disableButton.className = "button button1"
            disableButton.style.display = "";
            br1.style.display = "";
            br2.style.display = "";
        }
    });

There is more code below this, but it is functioning code that cannot be shared out.

Popup.html:

<button class="button button1" id="disableButton" style="display:none">Error</button>
    <br id="br1" style="display:none">
<br id="br2" style="display:none">

Background.js:

var isExtensionOn = true;

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){
    if (request.cmd == "setOnOffState") {
        isExtensionOn = request.data.value;
    }

    if (request.cmd == "getOnOffState") {
        sendResponse(isExtensionOn);
    }
});

Any help on this is greatly appreciated!

I am looking to add a disable button in the popup window of my chrome extension that will have it pause functionality like the Adblock extension does. This would remain paused in all tabs until the button is clicked to re-enable it. I have the following code in place, however, the button and functionality don't currently work.

Popup.js file:

function disableButton() {
    var disableButton = document.getElementById("disableButton");
    var isExtensionOn = true;
    if (disableButton.innerHTML == "Disable") {
        isExtensionOn = false;
    } else if (disableButton.innerHTML == "Enable") {
        isExtensionOn = true;
    } else {
        alert("Error");
    }
}

document.addEventListener('DOMContentLoaded', function () {
    var singleButton = document.getElementById("singleButton");
    var br1 = document.getElementById("br1");
    var br2 = document.getElementById("br2");
    //Sends message to event.js (background script) telling it to disable the
    chrome.extension.sendMessage({ cmd: "setOnOffState", data: {value: isExtensionOn} });

    chrome.extension.sendMessage({ cmd: "getOnOffState"}, function(response){
        console.log(response);
        if (response == true){
            disableButton.innerHTML = "Disable";
            disableButton.className = "button button3"
            disableButton.style.display = "";
            br1.style.display = "";
            br2.style.display = "";
        }
        if (response == false){
            disableButton.innerHTML = "Enable";
            disableButton.className = "button button1"
            disableButton.style.display = "";
            br1.style.display = "";
            br2.style.display = "";
        }
    });

There is more code below this, but it is functioning code that cannot be shared out.

Popup.html:

<button class="button button1" id="disableButton" style="display:none">Error</button>
    <br id="br1" style="display:none">
<br id="br2" style="display:none">

Background.js:

var isExtensionOn = true;

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){
    if (request.cmd == "setOnOffState") {
        isExtensionOn = request.data.value;
    }

    if (request.cmd == "getOnOffState") {
        sendResponse(isExtensionOn);
    }
});

Any help on this is greatly appreciated!

Share Improve this question edited Jan 30, 2018 at 15:22 BoffinBrain 6,5256 gold badges35 silver badges59 bronze badges asked Jan 30, 2018 at 15:16 Adam FlickemaAdam Flickema 2012 silver badges8 bronze badges 1
  • 1 What exactly "doesn't work"? – NikxDa Commented Feb 6, 2018 at 14:17
Add a comment  | 

3 Answers 3

Reset to default 12 +100

After going through the code that you have provided, it seems like there are some trivial misses that happened in the code, which led to the functionality failure.

I'll be pointing out the mistakes you have done here :

  • In Popup.js, the variable isExtensionOn has the functional scope of the disableButton(), and hence cannot be accessed inside the document.addEventListener('DOMContentLoaded', function () { }) event listener.

    The value of isExtensionOn inside this listener function would be undefined, which is not something that you expect in your system.

    To fix this, you just need to define the variable isExtensionOn on a level above (say global level), so that it is accessible to both function disableButton() { }) and the event listener of DOMContentLoaded.

  • In Popup.js, the function block chrome.extension.sendMessage({cmd: "getOnOffState"}, function (response) { }) contains a disableButton, which I see is nowhere defined within the functional scope of the event listener of DOMContentLoaded. And you are performing assignment to it, which would throw you errors in the console of whatever browser you are using which would look like:

    Uncaught ReferenceError: disableButton is not defined

    To fix this issue, you need to define the disableButton within the scope of the event listener of DOMContentLoaded.

  • In Popup.js, inside the event listener of DOMContentLoaded, you have defined a variable singleButton as var singleButton = document.getElementById("singleButton");, but I see that in the Popup.html file that you have provided, there is no element but the id of singleButton.

    This would return you a value of null, again which is something that you are not looking forward to have in your system.

    To fix this issue, you need to correct the id mentioned, as document.getElementById("disableButton"); within the scope of the event listener of DOMContentLoaded.

NOTE : I am mentioning some conventions that you can follow for better coding practises

  1. Naming for all the html files need to start with lower cases.
  2. Use === instead of == for strict comparision. Refer here for more details about the same.
  3. Use proper indentations so as to not miss out any braces or commit unintentional errors. (You had missed out a }) in the code block where you defined the event listener for DOMContentLoaded)

Hence to sum up, I am writing the entire code of all the files that you have mentioned here with the appropriate corrections:

popup.html :

<button class="button button1" id="disableButton" style="display:none">Error</button>
<br id="br1" style="display:none">
<br id="br2" style="display:none">

Popup.js :

var isExtensionOn = true;

function disableButton() {
    var disableButton = document.getElementById("disableButton");
    if (disableButton.innerHTML === "Disable") {
        isExtensionOn = false;
    } else if (disableButton.innerHTML === "Enable") {
        isExtensionOn = true;
    } else {
        alert("Error");
    }
}

document.addEventListener('DOMContentLoaded', function () {
    var disableButton = document.getElementById("disableButton");
    var br1 = document.getElementById("br1");
    var br2 = document.getElementById("br2");

//Send message to event.js (background script) telling it to disable the extension.

    chrome.extension.sendMessage({cmd: "setOnOffState", data: {value: isExtensionOn}});

    chrome.extension.sendMessage({cmd: "getOnOffState"}, function (response) {
        if (response !== undefined) {
            if (response) {
                disableButton.innerHTML = "Disable";
                disableButton.className = "button button3";
                disableButton.style.display = "";
                br1.style.display = "";
                br2.style.display = "";
            }
            else {
                disableButton.innerHTML = "Enable";
                disableButton.className = "button button1";
                disableButton.style.display = "";
                br1.style.display = "";
                br2.style.display = "";
            }
        }
    });
});

Background.js :

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.cmd === "setOnOffState") {
            isExtensionOn = request.data.value;
        }

        if (request.cmd === "getOnOffState") {
            sendResponse(isExtensionOn);
        }
    });

This should work as per your requirement. Please go through the answer and let me know if you face any more issues in this regard.

The part of the script you provide has a scoping error. See this line in the DOMContentLoaded event:

chrome.extension.sendMessage({ cmd: "setOnOffState", data: {value: isExtensionOn} });

As far as I can tell, there is no variable named isExtensionOn in that scope. It is defined in the function scope of disableButton (), but not in the event. Therefore, your script will tell the backend to set the variable to undefined.

When you then proceed to check the value against true and false, neither of that will be the value. That could cause the problem. To fix it, change {value: isExtensionOn} to {value: false}.

Second, you are using a button with the id singleButton, even though there is not a button with this id. You are assigning it to variable singleButton, but further down below, you are using a button called disableButton, which is not defined.

Also, your last line is missing closing parenthesis: }). After fixing all these issues, the plugin works just fine, I've tested it.

Tip:

You can debug your extension and view errors by opening the popup, right-clicking on it and then choosing Inspect Element. Switch to the console tab. It will have the JavaScript errors in it.

The popup window can access the background script directly, through chrome.runtime.getBackgroundPage, therefore making it way simpler:

popup.js

var backgroundPage;
var theButton = document.querySelector("button");

function updateButton(onOrOff){
    theButton.innerHTML = onOrOff ? "Disable" : "Enable";
    theButton.className = onOrOff ? "button button3" : "button button1";
}        

function toggleButton(){
    backgroundPage.isExtensionOn = !backgroundPage.isExtensionOn;
    updateButton(backgroundPage.isExtensionOn);
}

chrome.runtime.getBackgroundPage(function(bgPage) {
    backgroundPage = bgPage;
    updateButton(bgPage.isExtensionOn);
    theButton.onclick = toggleButton;
    theButton.style.display = "";
    document.getElementById("br1").style.display = "";
    document.getElementById("br1").style.display = "";
});

//the rest of your code just needs to check backgroundPage.isExtensionOn
//to see if the extension is on or not.

popup.html

<button class="button button1" id="disableButton" style="display:none">Error</button>
<br id="br1" style="display:none">
<br id="br2" style="display:none">
<script src="popup.js"></script>

background.js

var isExtensionOn = true;  //this will be changed by popup.js directly.
发布评论

评论列表(0)

  1. 暂无评论