Во-первых, добавьте в свой iframe событие onload, эта загрузка вызовет функцию с двумя целями:
- отправит сообщение в iframe, чтобы сообщить содержимому этого iframe, что оно былозагружено
- отправка страницы DOM в iframe при запросе
[родительский файл]
<iframe id="assessment" src="target.html" onload="check()">
...
</iframe>
, а также мы связываем то же действиев свойство window.onmessage
, так что будет обрабатываться каждое сообщение, полученное из iframe.
[родительский файл]
window.onmessage = function(event) {
check(event);
};
и функция:
[родительский файл]
function check(event) {
if(!event || !event.data){
// if the iframe is loaded, then tell it so
document.getElementById('assessment').contentWindow.postMessage('','*');
}else{
// if the Window received a message from the iframe, then send
// the page dom to the iframe
event.source.postMessage(document.body.innerHTML, event.origin);
}
}
И в iframe мы свяжем window.onmessage
с функцией, которая имеет двойную цель:
- подтвердите, что iframe был загружен, поэтому запрашивает данные у родителя
- получает дом от родителя
[дочерний файл]
window.onmessage = function(event) {
if(!event.data){
// If the iframe was loaded, tell the parent to send
// its dom
window.parent.postMessage('get parent DOM',event.origin)
}else{
// If the parent sent its DOM, process it
var dom = $('<div></div>').append(event.data);
console.log(dom.html());
...
}
};