最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Detect page change with javascript? - Stack Overflow

programmeradmin1浏览0评论

How to detect what page i am being redirected to using javascript.

$(window).on("onbeforeunload",()=>{
    alert("Something")
})

This code never executes (despite me reloading the page or clicking on other URLs). I am running my scripts on localhost. Also, i would like to know the URL of the page that i am being redirected to.

This is my full HTML:

<!DOCTYPE html>
<html>
    <head>
         <title>Practice</title>
         <script 
     src=".3.1/jquery.min.js"> 
        </script>
    </head>

<body>
    <script>
        $(window).unload(()=>{
            alert("Something");
        })

    </script>
    <a href = "http:\\www.youtube">Link</a>


</body>
</html>

How to detect what page i am being redirected to using javascript.

$(window).on("onbeforeunload",()=>{
    alert("Something")
})

This code never executes (despite me reloading the page or clicking on other URLs). I am running my scripts on localhost. Also, i would like to know the URL of the page that i am being redirected to.

This is my full HTML:

<!DOCTYPE html>
<html>
    <head>
         <title>Practice</title>
         <script 
     src="https://ajax.googleapis./ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script>
    </head>

<body>
    <script>
        $(window).unload(()=>{
            alert("Something");
        })

    </script>
    <a href = "http:\\www.youtube.">Link</a>


</body>
</html>
Share Improve this question asked May 5, 2018 at 6:58 ComputeshortsComputeshorts 6161 gold badge8 silver badges27 bronze badges 3
  • The event name is just beforeunload not onbeforeunload. But you're not allowed to call alert() during this, it should just return a string. – Barmar Commented May 5, 2018 at 7:00
  • Is there any way of detecting what URL i am being redirected to? – Computeshorts Commented May 5, 2018 at 7:02
  • 1 No, there isn't. – Barmar Commented May 5, 2018 at 7:03
Add a ment  | 

2 Answers 2

Reset to default 3

Maybe you can alert() or do whatever you want and then redirect to the url like the following example?

$('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;
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href = "https://stackoverflow./help/mcve">Link1</a>
<a href = "https://stackoverflow./help/deleted-questions">Link2</a>

In modern browsers(IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

if ("onhashchange" in window) {
  alert("The browser supports the hashchange event!");
}
function locationHashChanged() {
  if (location.hash === "#somecoolfeature") {
    somecoolfeature();
  }
}
window.onhashchange = locationHashChanged;
发布评论

评论列表(0)

  1. 暂无评论