google-chromegoogle-chrome-extension

Google Chrome extension: toggle on/off mode


I have a Google Chrome extension accessible from a button. The extension is supposed to "Start" something and then, when it is clicked again, it is supposed to "Stop". Thus, it must recognize its current state (and also present different popups depending on the state).

Is there a way to keep track of this global flag or variable?

My current manifest.json, which just shows a simple popup (a dialog for State #1):

{
  "name": "Test",
  "version": "1.0",
  "description": "Test",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "Test.png", 
    "default_popup": "popup1.html"
  }
}

The file "popup1.html" is just a page with an OK form button. When the OK button is clicked, it will set this global state variable to ON, and the next extension-button click will behave launch a different page.


Solution

  • Global variable will be re-initialized when you try to open a new popup. "localStorage" allows extension to save data on the client device. It only supports key-value mapping data now, e.g. localStorage.currentState = "start".

    You can use localStorage to save the button state and update the button status accordingly when user open the popup dialog.

    HTML

    <!--default status is start-->
    <button id="toggle-btn">ON</button>
    

    JS

    $(function(){
        //default value is "start"
        var currentState = localStorage.currentState || "start";
        //cache button DOM element reference
        var $toggleBtn = $("#toggle-btn");
    
        //update button status
        if(currentState==="stop"){
            $toggleBtn.text("OFF");
        }
    
        //register button click handler
        $toggleBtn.click(function(){
            if(currentState==="start"){
                $toggleBtn.text("OFF");
                localStorage.currentState="stop";
            }
            if(currentState==="stop"){
                $toggleBtn.text("ON");
                localStorage.currentState="start";
            }
        });
    });
    

    BTW, you can use browser dev tool (in resource tab) to check if the data is stored as expected.