tabs.executeScript – 传递参数和使用库?

我正在编写一个Chrome扩展程序,需要根据某个给定的参数修改特定域中的页面,这些参数需要XSS才能获得,所以简单地使用内容脚本似乎是不可能的。 所以,我决定使用tabs.executeScript注入脚本。

现在我需要知道两件事:首先,如何在使用executeScript时将参数传递给脚本? 我想我可以使用消息,但是在注入脚本时是不是有更直接的方法来传递参数?

其次,我的脚本使用jQuery,所以我需要以某种方式包含jQuery。 这很愚蠢,但我不知道该怎么做。 到目前为止,我在我编写的HTML页面中嵌入了jQuery(例如background.html)。

如果您不想使用消息传递,那么:

chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){ chrome.tabs.executeScript(tabId, {code: "var scriptOptions = {param1:'value1',param2:'value2'};"}, function(){ chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){ //all injected }); }); }); 

jquery.js应该放在扩展文件夹中)。 脚本选项将在script.js scriptOptions变量中提供。

通过消息传递,它同样简单:

 chrome.tabs.executeScript(tabId, {file: "jquery.js"}, function(){ chrome.tabs.executeScript(tabId, {file: "script.js"}, function(){ chrome.tabs.sendMessage(tabId, {scriptOptions: {param1:'value1',param2:'value2'}}, function(){ //all injected }); }); }); 

您需要向script.js添加请求侦听器:

 chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { var scriptOptions = message.scriptOptions; console.log('param1', scriptOptions.param1); console.log('param2', scriptOptions.param2); doSomething(scriptOptions.param1, scriptOptions.param2); }); 

基于上面的直接方法,我能够直接从Chrome扩展程序的后台脚本中将代码注入新选项卡。 但是,请注意,executeScript命令的代码部分不仅仅采用变量,而只采用字符串。 因此,经过实验,我发现我们需要事先设置命令串并包含我们想要的变量。 像这样:

 var sendCode = 'document.getElementsByClassName("form-control n-gram")[0].value = "' + TMObj.brand + '";'; var TMUrl = "http://website.com"; chrome.tabs.create({ url: TMUrl }, function(tab){ chrome.tabs.executeScript(null, {code: sendCode}); }); }); 

这很好用!