Ariel
Ariel

Reputation: 2808

Chrome extension problem with background page

I am trying to execute JavaScript code to the webpage when the user clicks the browser action. It worked very well, and when I tried to put it on the background page it messed up. I want specific code to execute once and when the icon is clicked again, different code to run. I tried to do the following.

//Background page
<Script>
    function goNow() {
        var live = 2;
        chrome.tabs.executeScript(null,
                                 {code:"Code"});
    }

    function Shutdown(){
         var live = 1;
         chrome.tabs.executeScript(null,
                                   {code:"Code"});
    }

    function runLive(live){
        if (live==1) {goNow()}
        else {Shutdown()}
    }

    chrome.browserAction.onClicked.addListener(runLive)

</script>

Of course that 'Code' is JavaScript code that works very well when injected into the page.

Upvotes: 1

Views: 542

Answers (1)

serg
serg

Reputation: 111255

  • chrome.browserAction.onClicked.addListener passes a tab object to a callback function, you can't just pass you own parameter there.

  • Declaring a variable inside a function (by using var keyword) makes it available only inside this function.

You code should be something like this:

//global variable 
var live = 1;

function goNow() {
    live = 2;
    chrome.tabs.executeScript(null, {code:"Code"});
}

function Shutdown(){
    live = 1;
    chrome.tabs.executeScript(null, {code:"Code"});
}

function runLive(tab){
    if(live==1){goNow()}
    else{Shutdown()}
}

chrome.browserAction.onClicked.addListener(runLive);

Upvotes: 3

Related Questions