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

问题描述 投票:0回答:1

我只有2条路线

/

/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?");
});
javascript jquery node.js ejs
1个回答
0
投票

您可以使用网址比较。

$(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?';
                }
            });
});
© www.soinside.com 2019 - 2024. All rights reserved.