如何在JS/Jquery中检测用户是否按下浏览器的后退/前进箭头for none SPA

w9apscun  于 5个月前  发布在  jQuery
关注(0)|答案(2)|浏览(97)

我只有两条路

/

字符串

/about


当我在URL

localhost:8080 -> it renders my home page
localhost:8080/about -> it renders about page


如果用户打开主页,点击关于按钮,并转到关于页面,而不是如果用户将点击浏览器的后退按钮,我想只是提醒“用户点击浏览器按钮”
我已经尝试了许多互联网解决方案,但没有一个工程尝试了这一点,但不工作。

$(window).on('popstate', function(event) {
  alert("You are going to back page. Can work that?");
});

pjngdqdw

pjngdqdw1#

你可以使用URL比较。

$(document).ready(function () {
    // Store the initial URL when the page loads
    var initialUrl = window.location.href;

    // Listen for beforeunload event
    $(window).on('beforeunload', function () {
        // Compare the current URL with the initial URL
        if (window.location.href !== initialUrl) {
            // Display alert if the user is navigating away
            return 'You are going to a different page. Are you sure you want to leave?';
        }
    });
});

字符串

u2nhd7ah

u2nhd7ah2#

popstate是专为SPA设计的,IOW:您的SPA页面路由将执行pushstate..您不会从非SPA应用程序中获得popstate
友情链接-> https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent
注:每次活动历史记录条目在同一文档的两个历史记录条目之间发生更改时,都会向窗口发送一个popstate事件。
注意-> same document,IOW:如果你导航到about而没有使用pushstate,那么它不是同一个文档。
SPA的工作原理是这样的->
1.使用新URL的pushstate
1.加载新URL的DOM内容。
按下后退按钮

  1. popstate被触发,加载新URL的内容
    所以你可以使用jQuery来做这件事,通常用户所做的是拦截a标签,使用preventDefault并执行上面的1,2。
    注意事项:beforeunload可以使用,但要注意它的同步和非常糟糕的用户体验,特别是使用alert。所以如果你能让push/popstate工作,你会发现你可以为用户创建更好的用户体验。例如。能够使用新的HTML Dialog元素-> https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

相关问题