我想出了以下解决方案-这仅是因为我们控制了 iframe 内容和主机窗口的内容
在 iframe 中,我们将以下脚本添加到页面页脚(所有页面使用相同的模板,因此这是对单个文件的更改)
<script>
window.onunload = function() {
// Notify top window of the unload event
window.top.postMessage('iframe_change', '*');
};
</script>
在主机窗口中,我们添加这个脚本来监控 iframe 状态
function init_content_monitor() {
var content = jQuery('.iframe');
// The user did navigate away from the currently displayed iframe page. Show an animation
var content_start_loading = function() {
alert ('NOW: show the animation');
}
// the iframe is done loading a new page. Hide the animation again
var content_finished_loading = function() {
alert ('DONE: hide the animation');
}
// Listen to messages sent from the content iframe
var receiveMessage = function receiveMessage(e){
var url = window.location.href,
url_parts = url.split("/"),
allowed = url_parts[0] + "//" + url_parts[2];
// Only react to messages from same domain as current document
if (e.origin !== allowed) return;
// Handle the message
switch (e.data) {
case 'iframe_change': content_start_loading(); break;
}
};
window.addEventListener("message", receiveMessage, false);
// This will be triggered when the iframe is completely loaded
content.on('load', content_finished_loading);
}