繁体   English   中英

beforeunload 事件和 Content-Disposition=attachment

[英]beforeunload event and Content-Disposition=attachment

我最近在我的代码中添加了这样的内容:

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

因此,只要用户 go 到我的 web 的另一侧,微调器就会出现。 它在大多数情况下都有效。 但是,在应用程序的某些部分,客户端开始转到另一端,服务器使用此标头响应:

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

这可以防止重新加载页面,并且只显示 window 以要求下载或打开文档。 我的问题是即使页面停止加载,微调器仍然显示

即使页面由于标题而没有重新加载,应该隐藏我的微调器的事件是什么?

您可以为下载链接添加属性目标。

例子:

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

属性target="_blank"将导致 onbeforeload 事件不会触发。

我们遇到了类似的问题,并找到了手动执行魔术(在您的情况下,显示微调器)的解决方案,例如:

 $('.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. 这个 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