【问题标题】:beforeunload event and Content-Disposition=attachmentbeforeunload 事件和 Content-Disposition=attachment
【发布时间】:2022-01-20 04:24:13
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 我不认为有任何事件你可以听这个。如果没有加载新页面,您最多可以尝试设置超时,并在一段时间后再次禁用微调器。或者,如果您知道哪些方式可以“离开”页面触发这样的特定响应,您可以尝试以某种方式确定(单击相应链接/提交按钮上的处理程序),并且在这些情况下不显示微调器开始。
  • 浏览器已经显示进度指示器。不要自己做。这是不好的用户体验实践,不应该这样做。

标签: javascript dom-events


【解决方案1】:

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

例子:

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

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

【讨论】:

  • 问题是没有总是一个按钮。另一方面,它是一个非常大的网站,我搜索了一个通用解决方案
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    1. 此 jquery 插件使用 window 对象将其 beforeunload 事件绑定到 body 元素,使其易于实现并提供通用解决方案。

    ;(function($, window, document){
    
      $.fn.plgn = function() {
    
        //Start the loader when the event beforeunload
        $(window).on('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="window.location.reload();" />

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2015-03-11
    • 2011-06-18
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2011-11-19
    相关资源
    最近更新 更多