3

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?

amiregelz
  • 1,833
  • 7
  • 25
  • 46

2 Answers2

2

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.

  • The questions is - is it possible to do with vanilla JS or with React? I don't want to create a Vue app for this :) – amiregelz Feb 13 '22 at 18:21
0

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);