Skip to content

Instantly share code, notes, and snippets.

@benjamingr benjamingr/FrameMonitor.js Secret
Last active Jun 1, 2019

Embed
What would you like to do?
{
// the idea is to keep a live collection of iframes and to check it against the ones we have
// already reported whenever a mutation occurs.
class FrameMonitor extends EventTarget {
static observerConfig = {
attributes: false,
childList: true,
characterData: false,
subtree: true,
};
constructor() {
super();
this.reportedFrames = new WeakSet();
this.liveFrames = document.getElementsByTagName('iframe');
this.deferredTimer = 0;
this.onMutations = this.onMutations.bind(this);
this.observer = new window.MutationObserver(() => {
clearTimeout(this.deferredTimer);
this.deferredTimer = setTimeout(this.onMutations);
});
}
onMutations() {
for(const frame of this.liveFrames) {
if (this.reportedFrames.has(frame)) {
continue;
}
this.reportedFrames.add(frame);
this.dispatchEvent(new CustomEvent("new-frame", { detail: frame }));
}
}
observe(root) {
this.observer.observe(root, this.constructor.observerConfig);
}
disconnect() {
this.observer.disconnect();
}
}
if(window.observer) {
window.observer.disconnect();
}
window.observer = new FrameMonitor();
window.observer.addEventListener('new-frame', e => {
console.log("Found new frame!", e.detail);
});
window.observer.observe(document.body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.