I use the following code to access a field (var addInfo) in an iframe via userscript in tampermonkey. The code currently works when the page is fully reloaded. However, it does not work if waitForKeyElements is triggered a second time by the MutationObserver. The MutationObserver itself works and would call the function, but it is not executed. What could be the reason?
// ==UserScript==
// @name _Wait for delayed or AJAX page load
// @version 0.1
// @description try to take over the world!
// @match https://urlFromPage/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design
change introduced in GM 1.0.
It restores the sandbox.
*/
/* global $, waitForKeyElements */
// Select the node that will be observed for mutations
const targetNode = document.getElementById("content");;
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type === 'attributes') {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
waitForKeyElements('#content > div > div > article', actionFunction, true, '#content > iframe');
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
function actionFunction() {
var frame = document.querySelector("#content > iframe");
var frameDoc = frame.contentDocument;
var body = frameDoc.getElementsByTagName("body");
var addInfo = frameDoc.getElementsByTagName("div")[25].innerHTML;
if (addInfo != null) {
alert(addInfo);
}
observer.disconnect();
}
It was because a separate HTML element with nested elements was created for each opened object. So i had to determine the active element in advance and access the required field in it