2015-12-14 99 views
-1

这是工作:Chrome扩展:问题与传递参数

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

这不是(编辑代码,便于):

function click(e) { 

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

我怎样才能正确地传递呢? 谢谢!

+0

什么是你看到的错误? – jianweichuah

+0

它说undefined,@jianweichuah –

+0

你有没有试过看'e'是什么?将'console.log(e)'添加到函数中,看看它是什么。 – jianweichuah

回答

0

找到一个解决办法:

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'}); 
    }); 
} 
1

我觉得你的问题是字符串值的格式不正确。例如,

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

是行不通的,因为当执行var money=test;,脚本不知道什么test是。

如果你想在传递一个字符串,它应该是

function click(e) { 

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

这样一来,执行的代码将会var money="test";

+0

可移植的方式是做一个JSON编码。看到重复。 – Xan