简体   繁体   中英

How to maintain the state of button in Chrome extension pop up once it is clicked.(JavaScript)

I am making a Chrome Extension which basically has a button. The button changes color and text on click and alternates between "Enable" and "Disable". See this fiddle for explanation and to see what I am talking about.

Now what I want is that once I click the button and it goes to disable condition, it should remain disabled until clicked again.How can I do it?

I know that whenever the extension popup is opened ,it is like a new page, so I would have to save the previous state using chrome.storage and load this state every time popup is clicked. I get a slight idea by this ans here. But I cannot wrap my head around it fully.

My manifest:

{
  "manifest_version": 2,

  "name": "Parental Control",
  "description": "This extension allows the user to change the background color of the current page.",
  "version": "1.0",
  "background":{
  "scripts": ["background.js"]
},
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "run_at": "document_start"
  },
  "permissions": [
    "tabs",
    "activeTab",
    "storage",
    "webRequest",
    "webRequestBlocking"
  ],
  "content_scripts": [
    {
        "matches": ["*://*/*"],
        "js": ["content_script.js"],
        "run_at": "document_end"
    }
]
}

popup.html:

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style type="text/css">
      body {
        width:200px;
        height:300px;
        white-space: nowrap;
       background: linear-gradient(0deg, rgba(248, 246, 242, 0.8), rgba(248, 246, 242, 0.8)), url(back_main.jpg) repeat;
      }
    </style>
    <link href="css/button.css" rel="stylesheet">
    <link href="css/logo.css" rel="stylesheet">
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
      <img src="icon.png" alt="Control" class="center" style="width:80px;height:80px;">
      <button class="button" style="vertical-align:middle" id="buttonclick">
  <span>Enable Control</span></button>
 <script type="text/javascript" src="popup.js"></script>
  </body>
</html>

popup.js:

document.addEventListener('DOMContentLoaded', function() {
    var click = document.getElementById("buttonclick")

    click.addEventListener("click", handler);
});
var count = 1;
    function handler() {
        var property = document.getElementById('buttonclick');
        if (count == 0) {
            property.style.backgroundColor = "#4f8ff7"
            property.innerHTML = "<span>Enable control</span>"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#a84237"
            property.innerHTML = "<span>Disable control</span>"

            count = 0;
        }
    }

If I am reading your code correctly, you are using 'count' like a boolean to indicate if the button is enabled or not. You should be able to achieve saved state by calling:

var obj = {};
obj['buttonState'] = count;
chrome.storage.sync.set(obj, function() {
  // this called after the save
});

To retrieve, you simply do the reverse:

chrome.storage.sync.get('buttonState', function(data) {   
    // this is called after the retrieve.
    count = data['buttonState'];
});

You're right that you need to use storage.local - you also need to allow for the value not being in storage yet, so the neatest way is to use the default value feature of the get function:

function handler() {
    chrome.storage.local.get({count: 0}, function (result) {
        var count = result.count;
        var property = document.getElementById('buttonclick');
        if (count == 0) {
            property.style.backgroundColor = "#4f8ff7"
            property.innerHTML = "<span>Enable control</span>"
            count = 1;
        }
        else {
            property.style.backgroundColor = "#a84237"
            property.innerHTML = "<span>Disable control</span>"
            count = 0;
        }
        chrome.storage.local.set({count: count});
    });
}

You could optimise by not bothering to set count and just using

chrome.storage.local.set({count: 1 - count});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM