当用户点击我的扩展程序的browserAction图标时,我会以编程方式加载代码,有时会有效,有时我会遇到jQuery is not defined
错误。
这是我的代码:
var injectElementLoaded = false;
chrome.browserAction.onClicked.addListener(function (tab) {
if (!injectElementLoaded) {
chrome.tabs.executeScript(tab.id, {file: "/resources/js/jquery-2.2.1.min.js"});
chrome.tabs.executeScript(tab.id, {file: "/resources/js/my_script.js"});
chrome.tabs.insertCSS(tab.id, {file: "/resources/css/my_script.css"});
norbertSidebarLoaded = true;
}
chrome.tabs.executeScript(tab.id, {code: "jQuery('body').trigger('execute-stuff')"}); // This is throwing issues
})
我在顶部正确定义了jQuery,但我猜测它还不够。
我想在我的上一个电话代码中添加setTimetout
,但我不知道要等多少。
有没有办法确保在调用最后一行之前加载我的脚本?
提前谢谢。
答案 0 :(得分:2)
您可以传递一个在执行脚本后调用的回调函数。也就是说,您应该重写上面的代码,如下所示:
var injectElementLoaded = false;
chrome.browserAction.onClicked.addListener(function (tab) {
var trigger = function() {
chrome.tabs.executeScript(
tab.id,
{code: "jQuery('body').trigger('execute-stuff')"}
);
};
if (!injectElementLoaded) {
chrome.tabs.executeScript(
tab.id,
{file: "/resources/js/jquery-2.2.1.min.js"},
function() {
chrome.tabs.executeScript(
tab.id,
{file: "/resources/js/my_script.js"},
function() {
chrome.tabs.insertCSS(
tab.id,
{file: "/resources/css/my_script.css"},
function() {
norbertSidebarLoaded = true;
trigger();
});
});
});
} else {
trigger();
}
});
如果我尝试申请ES2015 ......
var injectElementLoaded = false;
const executeScript = (tabId, file) => {
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(tabId, {file: file}, () => {
resolve();
});
});
};
const insertCSS = (tabId, file) => {
return new Promise((resolve, reject) => {
chrome.tabs.insertCSS(tabId, {file: file}, () => {
resolve();
});
});
};
const trigger = (tabId) => {
chrome.tabs.executeScript(
tabId,
{code: "jQuery('body').trigger('execute-stuff')"}
);
};
chrome.browserAction.onClicked.addListener(tab => {
if (!injectElementLoaded) {
executeScript(tab.id, "/resources/js/jquery-2.2.1.min.js")
.then(() => {
return executeScript(tab.id, "/resources/js/my_script.js");
}).then(() => {
return insertCSS(tab.id, "/resources/css/my_script.css");
}).then(() => {
norbertSidebarLoaded = true;
trigger(tab.id);
});
} else {
trigger(tab.id);
}
});
无论如何,你应该使用回调函数。