假设访问者访问了我的网站 example.com,然后在同一选项卡中访问了其他网站(可能通过单击我网页的任何链接或手动输入地址栏),然后他按下浏览器后退按钮并返回到我的网站示例.com
我怎样才能检测到用户使用后退按钮再次访问了我的网站?.
我在努力
与 Popstate :
window.addEventListener('popstate', function(event) {
if (event.state && event.state.source === 'example.com') {
console.log('User returned to example.com by clicking the back button');
}
});
带 onpopstate
window.onpopstate = function(event) {
if (event && event.state) {
console.log('User returned to example.com by clicking the back button');
}
};
有页面显示
window.addEventListener('pageshow', function(event) {
if (event.persisted) {
console.log('User returned to example.com by clicking the back button');
}
});
可悲的是,这些都不起作用!!
您可以使用window.performance
实现想要的输出<script>
if (window.performance && window.performance.navigation.type === 2) {
console.log('User returned to example.com by clicking the back button');
}
</script>