gene b.
gene b.

Reputation: 11974

Multiple JS Lines in Chrome.Tabs.ExecuteScript()

I have a Chrome Extension that performs some actions based on the button toggle (state 0/1).

The problem is that right now, it changes the color Red/Blue, but there are some other actions that need to happen. I can't find a way to refer to a separate multi-line script or file in Chrome.Tabs.ExecuteScript. Every example I've found on the Web only has a single command, which is useless for me! Splitting across lines doesn't work. There will be FOR-loops, IF-statements, and other complexity I want to inject.

Actions needed: (State=0) Red background, make all IMG tag invisible, etc. (State=1) Blue background, make all IMG tags visible, etc.

background.js

var state = 0;

function activate()
{

    if (state == 0)
    {
          chrome.tabs.executeScript({
            code: 'document.body.style.backgroundColor="red"'
          });       

        state = 1;
    }
    else
    {
          chrome.tabs.executeScript({
            code: 'document.body.style.backgroundColor="blue"'
          });       

        state = 0;
    }

}

chrome.browserAction.onClicked.addListener(activate);

Upvotes: 1

Views: 3270

Answers (1)

Xan
Xan

Reputation: 77482

Make a separate file with your commands, and execute it with

chrome.tabs.executeScript({
  file: 'content1.js'
});

If you need to pass parameters along, see this question.


Alternative solution is to have a single content script and pass commands to it using Messaging.

If your approach registers listeners, make sure to execute addListener only once.

Upvotes: 3

Related Questions