Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect page change with javascript?

Tags:

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.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>
like image 859
Computeshorts Avatar asked May 05 '18 06:05

Computeshorts


People also ask

How to detect page Change in JS?

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

How do I get the current URL?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.


2 Answers

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.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>
like image 181
Hikarunomemory Avatar answered Oct 11 '22 15:10

Hikarunomemory


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;
like image 31
Sagar Kharche Avatar answered Oct 11 '22 16:10

Sagar Kharche