在谷歌浏览器中通过executeScript注入多个脚本 [英] Injecting multiple scripts through executeScript in Google Chrome
问题描述
我需要以编程方式注入多个脚本文件(后跟代码片段) 从我的 Google Chrome 扩展程序进入当前页面.chrome.tabs.executeScript
方法允许对于单个 InjectDetails
对象(代表一个脚本文件或代码片段),以及在脚本之后执行的回调函数.当前答案建议嵌套 executeScript
调用:
I need to programmatically inject multiple script files (followed by a code snippet) into the current page from my Google Chrome extension. The chrome.tabs.executeScript
method allows for a single InjectDetails
object (representing a script file or code snippet), as well as a callback function to be executed after the script. Current answers propose nesting executeScript
calls:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
chrome.tabs.executeScript(null, { file: "master.js" }, function() {
chrome.tabs.executeScript(null, { file: "helper.js" }, function() {
chrome.tabs.executeScript(null, { code: "transformPage();" })
})
})
})
});
然而,回调嵌套变得笨拙.有没有办法抽象这个?
However, the callback nesting gets unwieldy. Is there a way of abstracting this?
推荐答案
这是我提出的解决方案:
This is my proposed solution:
function executeScripts(tabId, injectDetailsArray)
{
function createCallback(tabId, injectDetails, innerCallback) {
return function () {
chrome.tabs.executeScript(tabId, injectDetails, innerCallback);
};
}
var callback = null;
for (var i = injectDetailsArray.length - 1; i >= 0; --i)
callback = createCallback(tabId, injectDetailsArray[i], callback);
if (callback !== null)
callback(); // execute outermost function
}
接下来,InjectDetails
脚本的序列可以指定为一个数组:
Subsequently, the sequence of InjectDetails
scripts can be specified as an array:
chrome.browserAction.onClicked.addListener(function (tab) {
executeScripts(null, [
{ file: "jquery.js" },
{ file: "master.js" },
{ file: "helper.js" },
{ code: "transformPage();" }
])
});
这篇关于在谷歌浏览器中通过executeScript注入多个脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!