Detect Vue SPA url changes (listen to route updates)

2.2k Views Asked by At

I have my JavaScript script injected to an existing website and running on top of it.
The website is a SPA built with Vue.js.

I would like to detect url changes (routes) in this SPA and call my own function, passing the new url as parameter.

I tried listening to the following events (based on this and this):

window.addEventListener("hashchange", myFunc);
window.addEventListener("popstate", myFunc);

but myFunc doesn't get triggered at any point.

I also tried to do this with React (using react-router) but it didn't get any route update event.
Do I have to use Vue to achieve that?

2

There are 2 best solutions below

1
Yassin Shanwany On

In vue you can use the watcher property to watch for changes in any variable and handle them. in your application including route path and route params.

watch:{
  $route: {
    handler: function(newRouteValue){
      // put your code here
    },
    deep: true
  }
}

The deep in Vue watch is to watch for deep object changes. But you can remove it, if it is not necessary.

0
nosleepever On

As long as the pages have unique titles, you could use a mutation observer to watch for changes to the page's title, and upon a change, read the url and pass it into your function. Something like:

const config = { attributes: true, childList: true, subtree: true };

  let currentTitle;
  const pageTitle = document.querySelector('title');

  const callback = (mutationList, observer) => {
    mutationList.forEach((mutation) => {
      if (mutation.target.localName === 'title' && currentTitle !== mutation.target.innerText) {
        currentTitle = mutation.target.innerText;
        const currentUrl = window.location.href;
        myFunction(currentUrl);
      }
    });
  };

const observer = new MutationObserver(callback);

observer.observe(pageTitle, config);