简体   繁体   中英

How to store Firefox extension icon state locally

I have a firefox extension that can change the extension icon in the html options menu when you click on the icon image.

options.html

<body>
    <section class="browser-icons">
      <img id="black-trash" img src="../icons/black_trash.png" title="Black trash"/>
      <img id="red-trash" img src="../icons/red_trash.png" title="Red trash"/>
    </section>

options.js

const blackTrash = document.getElementById("black-trash"); 
const redTrash = document.getElementById("red-trash");
    
function setBlack() {
  browser.browserAction.setIcon({path:"../icons/black_trash.png"});
}
function setRed() {
  browser.browserAction.setIcon({path: "../icons/red_trash.png"});
}
    
blackTrash.addEventListener("click", setBlack);
redTrash.addEventListener("click", setRed);

However, if you change the icon to red, it resets to black (default) whenever you restart your browser.

How do I save the icon state locally?

Take a look: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage

I don't know exacly but try the localStorage to this -

function setBlack() {
  browser.browserAction.setIcon({path:"../icons/black_trash.png"});
  localStorage.setItem('icon', '../icons/black_trash.png');
}

To call this you will need only localStorage.getItem('icon');

I don't know if this solve your problem but we are here to learn too ;)

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