在chrome扩展中,在executeScript
函数中,我单击按钮,该按钮使用ajax渲染内容,我想要等待内容加载,然后单击另一个按钮:
在background.js脚本中我有:
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.update(tabs[0].id, {url: tabs[0].url}, function () {
chrome.tabs.executeScript({
file: "scriptInjection.js"
}, function (output) {
if (output == 'test1') {
sendData (output);
//clearStorage();
} else if (output == 'test2') {
sendData (output);
clearStorage();
}
});
});
});
我在scriptInjection.js
中尝试了很多东西,例如我创建了一个这样的暂停函数:
在 scriptInjection.js
文件中我有:
function pause(milliseconds) {
let dt = new Date();
while ((new Date()) - dt <= milliseconds) {
}
}
if (document.URL == "...") {
all = document.querySelectorAll('span.fc-title');
for (let i = 0; i < all.length; i++) {
if (all[i].innerText == 'company') {
all[i].click();
var result = true;
break;
}
}
if (result === true) {
pause(2000);
reserve();
output = 'test1';
} else {
document.querySelector("#calendar > div.fc-toolbar > div.fc-right > div > button.fc-next-button.fc-button.fc-state-default.fc-corner-right > span").click();
all = document.querySelectorAll('span.fc-title');
for (let i = 0; i < all.length; i++) {
if (all[i].innerText == 'company') {
all[i].click();
var result = true;
break;
}
}
if (result === true) {
pause(2000);
reserve();
output = 'test1';
}
}
}
但通过这种方式,脚本不会等到ajax内容加载,我使用setInterval作为保留功能,但它仍然不起作用。
我在 scriptInjection.js
文件中使用 MutationObserver,就像这样在 scriptInjection.js
的起点处使用,但它不起作用:
var observer = new MutationObserver(function () {
reserve();
});
observer.observe(document.documentElement, {attributes: true, childList: true, characterData: true});
和储备功能:
function reserve(){
let Shifts = document.getElementsByName("shifts");
if (Shifts.length !== 0) {
for (let i = 0; i < Shifts.length; i++) {
Shifts[i].click();
break;
}
document.querySelector("#Btn").click();
}
}
我阅读此链接以使用突变观察器“fjaguero.com/blog/using-mutationobservers-to-build-a-simple-extension/” 但我不知道在 chrome 扩展中将突变观察器放在哪里,我应该使用它的内容脚本还是执行脚本文件?
最佳答案
我不会在内容脚本上使用executeScript 功能。另外,总是更喜欢使用 the communication内容和后台脚本之间。
关于javascript - chrome扩展执行脚本等待ajax响应完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45119707/