区分文件下载与页面更改之前的卸载

问题描述 投票:23回答:2

我有一个onbeforeunload事件,该事件应该在用户进入新页面时触发。它运行良好,但是我发现只要用户从其所在页面下载文件,Chrome也会触发该事件。

我想知道事件是否被触发,因为它是由文件下载触发的。最好的方法是什么?

编辑:为澄清起见,我不拥有正在收听onbeforeunload的网站。正在第三方网站上安装的Javascript代码段监听了该事件。

javascript dom-events onbeforeunload
2个回答
0
投票

一个JavaScript解决方法

这是我能想到的唯一“干净”的方法,并且看起来还不错。


您的问题中的其他代码显示了您实际上如何使用“ onbeforeunload”很好。

但是我假设您正在使用类似下面的代码的游标“ loading ...”动画。

/* 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;
}

解决方案

第一步:

/* 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' );
});

第二步:

/* [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();
});

请注意,我使用$('html').addClass('cursor-loading-progress');,因为这是示例中预期的CSS,但是您现在可以做任何您想做的事情。


另外两个解决方法可能是:

  • 要在新选项卡中打开文件下载页面
  • 文件下载完成后触发页面刷新

17
投票

如果您将download =“ [FILENAME]”添加到标签中,似乎阻止了onbeforeunload的触发:

<a download="myfile.jpg" href="mysite.com">click me</a>

这是一个简单得多的解决方案。您可以不使用文件名,而只需说“下载”即可使用默认文件名。让我指出,这具有强制重新下载而不是使用缓存的副作用。我认为这是在2012年添加到chrome和ff中的。不确定Safari或ie的支持。

© www.soinside.com 2019 - 2024. All rights reserved.