【问题标题】:How to activate onbeforeunload after window.location reloads the page?window.location重新加载页面后如何激活onbeforeunload?
【发布时间】:2017-12-15 21:05:00
【问题描述】:

我在我的项目中使用onbeforeunload。但是有一个部分,用户可以单击链接并下载报告。在触发window.location 之前,我设置了window.onbeforeunload = null,这样用户就不会收到带有离开或留下问题的警报/确认框。一旦他们点击报告并下载文件,如果他们尝试关闭浏览器,就会出现问题onbeforeunload 不会再次触发。下载报告后如何触发onbeforeunload?这是我的功能示例:

function getReport(){
    var fileName = $(this).prop('id'),
    param = 'rptFile=' + fileName;  

    try{
        window.onbeforeunload = null;
        window.location = '/'+pathname+'/APPS/entry.cfm?idx=5&' + param;
    }catch(err){
        alert("An error occurred retrieving the file.");
    }
};

我正在重新加载entry.cfm 的主页有document.ready 功能,而我有onbeforeunload 功能。我预计一旦使用window.location 下载报告,onbeforeunload 将再次触发。所以我不确定我是否做错了什么,或者这对于 JS 是不可能的。这是entry.cfm 的例子:

$(document).ready(function() {
    window.onbeforeunload = function () {
        return 'Are you sure you want to leave?';
    }
});

如果有人知道如何再次触发 onbeforeunload,请告诉我。谢谢!

【问题讨论】:

  • 在 cookie 或 localstorage 中放置一些标志,以了解用户何时下载报告。如果确实如此,则再次附加 onbeforeload
  • @KresimirPendic 这就是我想知道如何再次附加onbeforeunload?我希望如果我在 document.ready 中有它会成功。
  • This may help you,另外,为什么不重新加载窗口,而是打开一个新窗口来下载报告或使用 iframe?

标签: javascript jquery onbeforeunload


【解决方案1】:

这会起作用,不要 null window.onbeforeunload 只需将您的 window.location 替换为 window.open 即可在新标签中打开报告。

function getReport() {
  try {
    window.open('https://via.placeholder.com/350x150/ee5533', '_blank');
  } catch (err) {
    alert("An error occurred retrieving the file.");
  }
};


window.onbeforeunload = function() {
  return 'Are you sure you want to leave?';
}

$('.dwl').on('click', getReport );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="dwl">Try to download in new tab</a>

【讨论】:

  • Kreimire 这行得通!谢谢你的帮助。我希望用户不会感到困惑,因为一旦他们点击链接,新窗口会在下载报告之前跳转一秒钟。
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 2011-10-09
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多