Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onchange event on window.location.href

I would like to trigger some Javascript function when window.location.href link changes. Is it possible?

Something like this:

$(window.location.href).on('change', function(){
   doSomething();
});
like image 600
Puchacz Avatar asked Nov 06 '14 21:11

Puchacz


People also ask

How do I change the location of a Windows href?

href = "https://www.example.com"; // Assigns a new URL to the current window. window. location. assign("https://www.example.com"); // Replaces the location of the current window with the new one.

What happens when you set window location href?

The location. href property sets or returns the entire URL of the current page.

Does window location href?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.


3 Answers

You said 'something like', given the example code you're probably looking for the onbeforeunload event handler.

From the Mozilla docs:

window.onbeforeunload = function(e) {   return 'Dialog text here.'; }; 
like image 164
elzi Avatar answered Sep 21 '22 07:09

elzi


The hashchange event occurs when there has been changes to the URL anchor part i.e after the #

window.addEventListener('hashchange', function() {      alert("Hash Changed");  }); 
like image 20
ashwin1014 Avatar answered Sep 18 '22 07:09

ashwin1014


There's no built-in event that gets triggered on all url changes. let's see why:

window.addEventListener('hashchange',listener)

  • triggers only when there's a change in hash (#) in URL.

window.addEventListener('popstate', listener);

  • triggers only when the user clicks the back button and not on pushState() or replaceState() event. Useless for SPA sites.

window.onbeforeunload()

  • won't work for SPA sites and on hashchange.

So, is there a way?
Yes, using MutationObserver:

let previousUrl = "";

const observer = new MutationObserver(() => {
  if (window.location.href !== previousUrl) {
    console.log(`URL changed from ${previousUrl} to ${window.location.href}`);
    previousUrl = window.location.href;
    // do your thing
  }
});
const config = { subtree: true, childList: true };

// start observing change
observer.observe(document, config);
like image 22
GorvGoyl Avatar answered Sep 21 '22 07:09

GorvGoyl