Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - mutation observer of iframe is removed when click a href of iframe?

After attach a mutation observer inside the iframe, does pressing the <a href=''> button inside the iframe remove the mutation observer?

I wrote the code to allow the mutation observer to detect changes of the body element, but it doesn't detect. I wonder if I wrote the wrong code or if what I thought above is correct.

If the mutation observer is deleted, should I register the mutation observer with the parent frame to which the iframe belongs?

let config = { attributes: true, childList: true, subtree: true, characterData: false };
let htmlBody = document.querySelector('body');

let observer = new MutationObserver(function(mutations, observer) {
    mutations.forEach(function(mutation) {
         console.log("Mutation calling");
    });
});

observer.observe(htmlBody, config);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

tl;dr: Yes, the injected javascript is lost when navigation occurs.

Javascript is generally tied to the document, not the container (i.e: the browser, the iframe, etc.). Normally, when navigation occurs, any javascript running in that context is unloaded in order to prepare for the new document and its new javascript.

This doesn't change in the case of an iframe. The iframe is the viewing context and the iframe's document is still a document and still has the same semantics as it would had it been loaded normally. Being able to inject code into that document doesn't change things.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...