简体   繁体   English

beforeunload 事件和 Content-Disposition=attachment

[英]beforeunload event and Content-Disposition=attachment

I recently add on my code something like this:我最近在我的代码中添加了这样的内容:

$(window).on('beforeunload', function () {
    $('.whirly-loader').show(); //SPINER
})

So anytime the user go to another side of my web the spinner show up.因此,只要用户 go 到我的 web 的另一侧,微调器就会出现。 And it works most of the time.它在大多数情况下都有效。 But, in some part of the app the client start going another side and the server response with this headers:但是,在应用程序的某些部分,客户端开始转到另一端,服务器使用此标头响应:

Cache-Control
    max-age=0, must-revalidate, private
Connection
    Keep-Alive
Content-Disposition
    attachment;filename=suministro.csv
Content-Type
    text/csv; charset=utf-8
[...]

This prevents the reload of the page and only show up the window to ask to download or open the document.这可以防止重新加载页面,并且只显示 window 以要求下载或打开文档。 My problem is the spinner still show up even if the page stop load我的问题是即使页面停止加载,微调器仍然显示

Which should be the event to hide my spinner even if the page don't reload because of the headers?即使页面由于标题而没有重新加载,应该隐藏我的微调器的事件是什么?

You can add attribute target for download links.您可以为下载链接添加属性目标。

Example:例子:

<body onbeforeunload="document.body.style.backgroundColor = 'red';">
    <a href="output.zip" target="_blank">Download</a>
</body>

Attribute target="_blank" will cause, that onbeforeload event will not fire.属性target="_blank"将导致 onbeforeload 事件不会触发。

We had a similar problem and came to the solution to do magic (in your case, show a spinner) manually, like:我们遇到了类似的问题,并找到了手动执行魔术(在您的情况下,显示微调器)的解决方案,例如:

 $('.js-show-spinner').addEventListener('click', event => { event.preventDefault(); $('.whirly-loader').show(); //SPINER });
 <a href="https://google.com">google.com</a> <a class="js-show-spinner" href="/home">Home</a> <a href="SOME_DOC" download>some doc</a>

  1. This jquery plugin uses the window object to bind it's beforeunload event to the body element making it easy to implement and offer aa generic solution.这个 jquery 插件使用 window object 将它的 beforeunload 事件绑定到 body 元素,使其易于实现并提供通用解决方案。
     ;(function($, window, document){ $.fn.plgn = function() { //Start the loader when the event beforeunload $(window).bind('beforeunload', function(event){ event.stopPropagation(); console.log("whirly-loader show"); //Hide the loader after 5 seconds if the page fails to load setTimeout(function(){ console.log("whirly-loader hide"); }, 5000); }); } })(jQuery, window, document); //Start the loader as soon as javascript loads console.log("whirly-loader show"); $( document ).ready(function() { //Hide the loader when the page is completely loaded console.log("whirly-loader hide"); $("body").plgn(); });
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="button" value = "Refresh page" onclick="history.go(0)" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM