in a chrome extension, in the executeScript function the script click on the button of the web page for example a button in the sitepoint.com, this button render content with ajax so the script must wait content load and then click in an another button: in the background.js script i have:
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();
}
});
});
});
i try a lot of things in scriptInjection.js
for exmple i create a pause function like this: in the scriptInjection.js file i have:
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';
}
}
}
but in this way the script dose not wait until ajax content loaded, i use setInterval for reserve function but still it dose not work i think because javascript is asyncronous and dose not wait until this content load via ajax, i use MutationObserver in the scriptInjection.js file like this at the start point of the scriptInjection.js but it dose not work:
var observer = new MutationObserver(function () {
reserve();
});
observer.observe(document.documentElement, {attributes: true, childList: true, characterData: true});
and the reserve function:
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();
}
}
i read this link to use mutation observer βfjaguero.com/blog/using-mutationobservers-to-build-a-simple-extension/β but i dont know where to place mutation observer in the chrome extension should i use it in the execute script file (scriptinjection.js)? plz help me on this issue or say what is the correct way to do this thing