简体   繁体   中英

How can I observe changes to the DOM in an iframe?

I'm using Jquery-Mutation Summary https://code.google.com/p/mutation-summary/ "a JavaScript library that makes observing changes to the DOM fast, easy and safe"

It can be found here: https://github.com/joelpurra/jquery-mutation-summary

Here's an example of it at work: http://joelpurra.github.io/jquery-mutation-summary/example/demo.html

I'd like to be able to observe changes to the DOM in an iframe from a parent window. Here's my code

$(function() {
var $ChangeThere = $('#myframe') //iframe id myframe
    $ChangeThere.mutationSummary('connect', callback, [{
    all: true
}]);
function callback(summaries){
//something changes in iframe dom
    alert('change!');
}
});

The above code doesn't work. I'm accessing from the same domain as well.

You should be able do the listening within the iFrame, then send the results back to the parent. You can establish a function in the parent, then update it from the iFrame like below.

Parent:

function alertfromiframe(message){
    alert(message);
}

iFrame:

$(function() {
var $ChangeThere = $('#frameContents') //iframe id myframe
    $ChangeThere.mutationSummary('connect', callback, [{
    all: true
}]);
function callback(summaries){
//something changes in iframe dom
    parent.alertfromiframe('change!');
}
});

expose a method from a page that will be loaded as an iframe:

var RPC = require('frame-rpc');
var origin = document.referrer;

var rpc = RPC(window, window.parent, origin, {
    beep: function (n, cb) {
        document.querySelector('#n').textContent = n;
        cb(n * 111);
    }
});

then from the parent page containing the iframe:

var RPC = require('frame-rpc');
var frame = document.querySelector('iframe');
var usrc = new URL(frame.getAttribute('src'));
var origin = usrc.protocol + '//' + usrc.host;

frame.addEventListener('load', function (ev) {
    var rpc = RPC(window, frame.contentWindow, origin);
    rpc.call('beep', 5, function (result) {
        document.querySelector('#result').textContent = result;
    });
});

The module you can find here: substack/frame-rpc You can use wzrd.in/standalone/frame-rpc or

npm install frame-rpc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM