如何检测浏览器会话历史导航并解决popstate事件不触发问题?
问题:popstate事件在浏览器导航按钮操作时未触发,无法实现登出后导航限制需求
我需要检测用户通过浏览器导航按钮操作会话历史的行为,实现登出后用户仅能访问登录页,导航按钮默认指向登录页。已知通过给popstate事件添加window.addEventListener()监听器可实现该功能,我已基于MDN示例编写了处理程序,但遇到了问题。
环境
- VS Code v1.83.0(搭配Live Server运行)
- Edge 117.0.2045.60(正式版,64位)
问题现象
调用history.pushState()等方法添加历史记录时,popstate事件能正常触发;但注释掉这些历史操作方法后,仅通过<a>标签跳转页面,再操作浏览器导航按钮(后退/前进)时,popstate事件完全不触发。根据资料描述:“popstate事件会在浏览器操作(如点击后退/前进按钮,或调用history.back()/history.forward())时触发”,但实际未符合预期。
相关代码
Index页面(index.html)
<!DOCTYPE html> <html lang="en"> <!-- Demonstrate using window.addEventListener() to process popstate events. Based on: https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event Oct 7, 2023. --> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo using addEventListener to process popstate events.</title> </head> <body id="myBody"> <h3>This is the Index Page</h3> <a href="/page1.html">Go to page 1</a> <p>Use the navigation buttons to trigger "popstate" events</p> <script src="./index.js"></script> </body> </html>
跳转目标页面(page1.html)
<!DOCTYPE html> <html lang="en"> <!-- Demonstrate using window.addEventListener() to process popstate events. Oct 7, 2023. --> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo using addEventListener() to process popstate events. Page-1</title> </head> <body id="myBody"> <h3>This is Page-1</h3> <p>Use the back navigation button to return to the Index page and trigger a "popstate" event</p> </body> </html>
JavaScript文件(index.js)
window.addEventListener('popstate', (event) => { console.log( `location: ${document.location}, state: ${JSON.stringify(event.state)}`, ); }); // history.pushState({ page: 1 }, "title 1", "?page=1"); // history.pushState({ page: 2 }, "title 2", "?page=2"); // history.replaceState({ page: 3 }, "title 3", "?page=3"); // history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" // history.back(); // Logs "location: http://example.com/example.html, state: null" // history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
内容的提问来源于stack exchange,提问作者Arebus
相关产品推荐
相关产品推荐

