Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...