我可以在javascript中取消location.href吗? [英] Can I cancel location.href in javascript

查看:290
本文介绍了我可以在javascript中取消location.href吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来可能很傻,但我需要这个功能。

It might sound silly, but I need this functionality.

一旦执行,我可以以某种方式取消javascript中的location.href ='url'吗?

例如单击按钮我正在使用一些资源密集型页面更改当前页面,我想为用户提供一个选项,以便在下一页需要很长时间加载时可以取消它。

for example on click of button i am changing current page with some resource intensive page, I want to give an option to user so that one can cancel it if next page is going to take long time to load.

谢谢和问候

推荐答案

是的,你可以。您可以使用 beforeunload 事件显示用户可以确认或取消的警报。当用户取消它时,页面导航将被取消。

Yes you can. You can use the beforeunload event to display an alert that the user can confirm or cancel. When the user cancels it, the page navigation is canceled.

示例:

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

请注意,并非所有浏览器都以相同的方式实现此功能,Chrome要求您设置 returnValue 触发警报的事件属性,即使HTML规范说你应该调用 event.preventDefault()来触发它。

Note that not all browsers implement this the same way, and Chrome requires you to set the returnValue property on the event to trigger the alert even though the HTML spec says that you should call event.preventDefault() to trigger it.

这篇关于我可以在javascript中取消location.href吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆