我可以在 Javascript 中取消 location.href

Sof*_*tic 4 javascript dom-events

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

我可以在 JavaScript 执行后以某种方式取消 location.href = 'url' 吗?

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

Pru*_*der 6

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

例子:

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

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