I've created a Google Chrome Extension that checks for DOM changes on a website (creation of divs, deletion of divs or updation of class names of divs). The code I'm using for that is:
function changestatus(){//code here}
function handleDivChanges() {
const sites = [
"https://www.site1.com/play/*",
"https://www.site1.com/game/*",
];
var status = getCookie('status');
return new Promise((resolve, reject) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
var currentWebsite = tabs[0].url;
const isMatch = sites.some(pattern => {
const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
const tab = tabs[0];
if (regex.test(currentWebsite) && (status == 'on')) {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: getHTMLData
}, (injectionResults) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
} else {
resolve(injectionResults[0].result);
}
});
}
});
function getHTMLData() {
function isPieceClassName(class_name) {
var tokens = class_name.split(" ");
if (tokens.length != 3) {
return false;
}
var piece_type = tokens.find(function (token) {return token.length == 2});
var piece_position = tokens.find(function (token) {return token.startsWith("square")});
return piece_type != undefined && piece_position != undefined;
}
var observer_config = {
attributes: true,
subtree: true,
attributeOldValue: true,
attributeFilter: ['class']
};
var observer = new MutationObserver(function (mutations) {
if (mutations.some(function(mutation) {
return (
(mutation.oldValue == "board" || mutation.oldValue == "board-flipped")
&& mutation.target.className != mutation.oldValue
)
})) {
}
var move_mutation = mutations.filter(function(mutation) {
return (
isPieceClassName(mutation.oldValue) &&
isPieceClassName(mutation.target.className)
)
});
if (move_mutation.length > 0) {
console.log("Move detected!");
changestatus();
}
});
var board = document.documentElement;
observer.observe(board, observer_config);
}
});
});
}
handleDivChanges();
The 'Move Detected' statement is logged however the changestatus()
function doesn't run saying it cannot find any such function.
I understand that the getHTMLData() function runs on a different scope and hence cannot read the changestatus() function, and so I'm looking for solution to be able to run the function inside off getHTMLData().
Thanks for your time!
PS: I cannot add changestatus() function inside off getHTMLData() as the changestatus() for one uses promises and secondly the changestatus() uses other functions which in turn use more functions that requires promises. I inturn require another solution to call the changestatus() function.