区分文件下载与页面更改的onbeforeunload

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或支持.

  • 这可以很好地与`target ="_ blank"一起使用,这有助于浏览器不支持`download`,就像所有Internet Explorer版本一样.对于那些它短时间打开一个新标签.那些具有适当"下载"支持的用户将立即开始下载,不会打开新标签. (5认同)
  • 这似乎在Chrome中不再起作用。 (2认同)

Adr*_* Be 1

JavaScript 解决方法

这是我能想到的唯一“干净”的工作,而且看起来效果很好。


您的问题中的更多代码显示您实际如何使用“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,但此时您可以执行任何您喜欢的操作。


另一些解决方法可能是:

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