How to detect changes in an iframe’s innerHTML and run a function with Mutationobserver?

Asked

Viewed 36 times

0

I’m creating an extension for Chrome and I need it to detect (within an iframe) when an object’s innerHTML is changed and performs an action, example: button.click();.

How can I create this condition? I searched on the Internet and even here on SOF but found no simple example demonstrating this kind of situation.

I have already created a web page with a random counter that changes every 5 seconds, now I need to detect whenever there is this change and perform a function.

Follows my code (also in Jsfiddle):

var iframe = window.frames[0];

iframe.document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM completamente carregado e analisado");

// cria uma nova instância de observador
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });
    });


    function verificavar() {
        var numeros = iframe.document.getElementById("contador").innerHTML;
        if(!numeros) {
            //The node we need does not exist yet.
            //Wait 500ms and try again
            window.setTimeout(verificavar,500);
            return;
        }


    // configuração do observador:
    var config = { 
        attributes: true, childList: true, characterData: true 
    };
    
    // passar o nó alvo, bem como as opções de observação
    observer.observe(numeros, config);

}
verificavar();

});
<iframe src="https://ipaymobile.000webhostapp.com">
</iframe>

  • Roger I think I’ve already commented on this in another question of yours:https://answall.com/questions/498926/script-para-clicar-em-um-bot%C3%a3o-dentro-de-um-iframe#comment924605_498926 if you haven’t read research on iframe and cross side script

  • @Ricardopunctual I saw your comment yes, but I already managed to solve that problem. My extension can already access the iframe and click on the buttons inside it, but I still don’t understand how Mutationobserver works and I need it to detect changes in innerHTML so when a data change, I run my script to click a button.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.