-1

This is working:

function click(e) {
    chrome.tabs.executeScript(null, {
        code: 'var money = 1;'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'peace.js'});
    });
}

This is not (edited the code for ease):

function click(e) {

    var test = 'test';
    chrome.tabs.executeScript(null, {
        code: 'var money = ' + test + ';'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'peace.js'});
    });
}

How can I pass it correctly? Thanks!

Sam
  • 900
  • 10
  • 18

2 Answers2

1

I think your problem is the string value is not formatted correctly. For example,

function click(e) {
    var test = 'test';
    chrome.tabs.executeScript(null, {
        code: 'var money = ' + test + ';'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'peace.js'});
    });
}

Wouldn't work because when var money=test; is executed, the script doesn't know what test is.

If you wanna pass a string over, it should be

function click(e) {

    var test = 'test';
    chrome.tabs.executeScript(null, {
        code: 'var money = "' + test + '";'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'peace.js'});
    });
}

This way, the executed code will be var money="test";

jianweichuah
  • 1,417
  • 1
  • 11
  • 22
0

Found a workaround:

if (e.target.id == 'test1') {
    chrome.tabs.executeScript(null, {
        code: 'var money = 1'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'peace.js'});
    });
} else  if (e.target.id == 'test2') {
    chrome.tabs.executeScript(null, {
        code: 'var money = 2'
    }, function() {
        chrome.tabs.executeScript(null, {file: 'test.js'});
    });
}
Xan
  • 74,770
  • 16
  • 179
  • 206
Sam
  • 900
  • 10
  • 18