I need to add some code to a webpage when a certain text appears on it.
So I load a webpage, and this appears:
<div id="someid" class="someclass" style=""></div>
I don't want anything to happen. But at some point this appears:
<div id="someid" class="someclass" style="">Some text here...</div>
When the text appears, I want Greasemonkey to add this somewhere on the page.
<div id="idbla">This is text...</div>
I don't care where this is added. It doesn't need to be appended to anything. It doesn't even need to be visible on the page. I just want it to appear somewhere in the HTML of the webpage.
Use a MutationObserver to detect text changes to your element:
function main() {
console.log('Text added!');
}
const wantedDiv = document.querySelector('#someid');
const button = document.querySelector('#add-text');
button.addEventListener('click', () => wantedDiv.innerText = 'text...');
const observer = new MutationObserver(() => {
if (wantedDiv.innerText) main();
observer.disconnect();
});
const config = {
characterData: false,
attributes: false,
childList: true,
subtree: false
};
observer.observe(wantedDiv, config);
<div id="someid" class="someclass" style=""></div>
<button id="add-text">Add text</button>