dsh*_*per 23 javascript onbeforeunload javascript-events
我有一个onbeforeunload事件,应该在用户进入新页面时触发.它运行良好,但我发现只要用户从他们所在的页面下载文件,它也会在Chrome中被触发.
我希望能够判断事件是否被解雇,因为它是由文件下载触发的.最好的方法是什么?
编辑:作为澄清,我不拥有我正在听的网站onbeforeunload.该事件由第三方网站上安装的Javascript片段收听.
jsa*_*rma 17
如果你将download ="[FILENAME]"添加到a标签,它似乎可以防止onbeforeunload被触发:
<a download="myfile.jpg" href="mysite.com">click me</a>
Run Code Online (Sandbox Code Playgroud)
这是一个更简单的解决方案.您可以不使用文件名,只需说"下载"即可使用默认文件名.让我指出这有强制重新下载而不是使用缓存的副作用.我认为这在2012年被添加到chrome和ff.不确定safari或支持.
这是我能想到的唯一“干净”的工作,而且看起来效果很好。
您的问题中的更多代码显示您实际如何使用“onbeforeunload”会很棒。
但我假设您正在使用类似下面代码的光标“正在加载...”动画。
/* Loading Progress Cursor
*
* Tested on: IE8, IE11, Chrome 37, & Firefox 31
*
* [1] the wildcard selector is not performant but unavoidable in this case
*/
.cursor-loading-progress,
.cursor-loading-progress * { /* [1] */
cursor: progress !important;
}
Run Code Online (Sandbox Code Playgroud)
第一步:
/* hooking the relevant form button
* on submit we simply add a 'data-showprogresscursor' with value 'no' to the html tag
*/
$(".js-btn-download").on('submit', function(event) {
$('html').data('showprogresscursor', 'no' );
});
Run Code Online (Sandbox Code Playgroud)
第二步:
/* [1] when page is about to be unloaded
* [4] here we have a mechanism that allows to disable this "cursor loading..." animation on demand, this is to cover corner cases (ie. data download triggers 'beforeunload')
* [4a] default to 'yes' if attribute not present, not using true because of jQuery's .data() auto casting
* [4b] reset to default value ('yes'), so default behavior restarted from then on
*/
var pageUnloadOrAjaxRequestInProgress = function() {
/* [4] */
var showprogresscursor = $('html').data('showprogresscursor') || 'yes'; /* [4a] */
if( showprogresscursor === 'yes' ){
$('html').addClass('cursor-loading-progress');
}
else {
$('html').data('showprogresscursor', 'yes' ); /* [4b] */
}
}
$( window ).on('beforeunload', function() { /* [1] */
pageUnloadOrAjaxRequestInProgress();
});
Run Code Online (Sandbox Code Playgroud)
请注意,我使用$('html').addClass('cursor-loading-progress');的是我的示例中预期的 CSS,但此时您可以执行任何您喜欢的操作。
另一些解决方法可能是: