如何使用javascript检测我被重定向到的页面。
$(window).on("onbeforeunload",()=>{
alert("Something")
})
Run Code Online (Sandbox Code Playgroud)
此代码永远不会执行(尽管我重新加载页面或单击其他 URL)。我在本地主机上运行我的脚本。另外,我想知道我被重定向到的页面的 URL。
这是我的完整 HTML:
<!DOCTYPE html>
<html>
<head>
<title>Practice</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<script>
$(window).unload(()=>{
alert("Something");
})
</script>
<a href = "http:\\www.youtube.com">Link</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
也许您可以alert()或做任何您想做的事情,然后重定向到url类似以下示例的内容?
$('a').on('click', function(e){
e.preventDefault();
let url = this.href;
alert(`You're leaving this page, would be redirected to : ${url}`)
window.location.href = url;
})Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href = "https://stackoverflow.com/help/mcve">Link1</a>
<a href = "https://stackoverflow.com/help/deleted-questions">Link2</a>Run Code Online (Sandbox Code Playgroud)