1

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);
gene b.
  • 10,512
  • 21
  • 115
  • 227

1 Answers1

3

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.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • MDN is also a good source for documentation and examples :) https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/executeScript – gal007 May 25 '16 at 12:37