Javascript 就在卸载事件之前的 iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30718692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:38:40  来源:igfitidea点击:

iframe just before unload event

javascriptjqueryhtmliframe

提问by Max

I need to capture an event which should be triggered just before the content of the iframe disappears.

我需要捕获一个应该在 iframe 的内容消失之前触发的事件。

I have been trying to accomplish something like this

我一直在努力完成这样的事情

$iframe = $('iframe');
$iframe.beforeunload(function () {
  debugger;
});

OR

或者

$iframe = $('iframe');
$iframe.unload(function () {
  debugger;
});

I have even tried binding it to the iframe window itself without any luck

我什至尝试将它绑定到 iframe 窗口本身而没有任何运气

$iframe = $('iframe');
$iframe[0].contentWindow.onunload = function () {
  debugger;
};

None of these eventhandlers actually trigger for me

这些事件处理程序实际上都没有为我触发

and I am quite confused why. To reload the iframe I use .reload()from outside the iframe and from within, maybe I need to use a different method?

我很困惑为什么。要从 iframe.reload()外部和内部重新加载我使用的 iframe,也许我需要使用不同的方法?

回答by Max

Figured it out! I didn't know the contentWindowlooses its reference after a reload.

弄清楚了!我不知道contentWindow重新加载后会丢失其参考。

$iframe.load(function () {
  $iframe[0].contentWindow.onbeforeunload = function () {
    debugger;
  };
});