简体   繁体   中英

Google Chrome Extension: Toggling a Function

I'm just starting out with javascript. My chrome extension is currently functioning but I'd like to add more functionality to it. When clicked, it runs this in background.html:

chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, { file: "hello.js" });
});

If I wanted to have the button toggle between hello.js script and goodbye.js; how would I accomplish this?

if (localStorage["toggle"] && localStorage["toggle"]=="hello"){
    alert("Good Bye");
    localStorage["toggle"]="goodbye";
} else {
    alert("Hello");
    localStorage["toggle"]="hello";
}

Thats how Id do it in the popup of a Browser Actions html/js.
If your doing it from the background then just change the localStorage to a variable.

var toggle;

chrome.browserAction.onClicked.addListener(function (tab) {

if (toggle=="hello"){
    chrome.tabs.executeScript(null, { file: "goodbye.js" });;
    toggle="goodbye";
} else {
    chrome.tabs.executeScript(null, { file: "hello.js" });
    toggle="hello";
}

});

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