React,检测用户是否要离开当前页面

时间:2018-02-13 10:02:13

标签: javascript reactjs

您好,谢谢您的时间!

我正在学习遵循React课程:https://app.pluralsight.com/library/courses/react-flux-building-applications/table-of-contents

看起来反应路由器API自编写课程后发生了很大的变化。

在课程中讲授如何使用willTransitionFrom和willTransitionTo,它们看起来都被弃用了:https://github.com/ReactTraining/react-router/issues/1388

我想跟随,如果用户要离开当前页面,我已尝试进行检测。我做了:

<a href="//www.reddit.com/submit" onclick="window.location = '//www.reddit.com/submit?url=' + encodeURIComponent(window.location); return false"> <img src="//www.redditstatic.com/spreddit10.gif" alt="submit to reddit" border="0" /> </a>

还有:

  window.addEventListener('beforeunload', (event) => {
    if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
        event.preventDefault();
    }
});

看起来它们都没有被触发,因为我想在您尝试加载其他页面时显示确认对话框。

我看过: How to check if user is refreshing the page or navigating to other page How to display a pop up, when a user tries to leave the current page? https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个(从https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload中挑选)

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
  return confirmationMessage;              // Gecko, WebKit, Chrome <34
});