Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - tabs.executeScript - passing parameters and using libraries?

I am writing a Chrome extension that needs to modify pages in a specific domain according to some given parameter, which needs XSS in order to be obtained, so simply using a content script seems impossible. So, I've decided to inject the script using tabs.executeScript.

Now I need to know two things: First, how can I pass parameters to the script when using executeScript? I guess I can use messages, but isn't there a more direct way to pass the parameter while injecting the script?

Second, my script uses jQuery, so I need to include jQuery somehow. It's silly, but I'm not sure how to do it. So far, I embedded jQuery in the HTML page I was writing (for example background.html).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't want to use messaging then:

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 should be placed into extension folder). Script options will be available inside scriptOptions variable in the script.js.

With messaging it is just as easy:

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

You would need to add a request listener to 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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...