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

Gad*_*i A 27 javascript jquery google-chrome google-chrome-extension

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

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

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

ser*_*erg 49

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

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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

(jquery.js应放入扩展文件夹).脚本选项将在scriptOptions变量中可用script.js.

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

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
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

您需要添加一个请求侦听器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);
});
Run Code Online (Sandbox Code Playgroud)