我想在用户点击后退/前进按钮重定向后时执行js函数。我有下面的半工作功能:
detectHistoryEvent();
function detectHistoryEvent() {
console.log(performance.navigation.type); // deprecated
console.log(performance.getEntriesByType("navigation")[0].type); // currently used
if (performance.getEntriesByType("navigation")[0].type && performance.getEntriesByType("navigation")[0].type === 'back_forward') {
themethod(); // method I want to run
}
}
工作场景1:
PAGE 1
用户单击执行 POST REQUEST
的删除按钮。PAGE 2
。PAGE 2
当用户单击后退按钮时,它将重定向到 PAGE 1
。重定向后,会因为上面的函数而执行themethod()
。这是因为导航的价值是back_forward
。不工作场景2:
PAGE 1
用户单击执行 GET REQUEST
的 href。PAGE 2
。PAGE 2
当用户单击后退按钮时,它将重定向到 PAGE 1
。然而 themethod()
并没有被执行。这是因为 nagivation 的值是 navigate
就像普通的 href 点击一样。即使
PAGE 1
执行GET REQUEST
,是否可以检查用户是否单击后退/前进按钮?
经过几天的搜索,删除了我的问题上的方法,并使用下面的代码来使用解决方案:
window.onpageshow = function(event) {
if (event.persisted) {
themethod();
}
};