Unable to detect manual URL change in address bar for SPA in jQuery

361 Views Asked by At

I'm trying to build a search engine UI as a single page application using jQuery.

I'm using fetch API for loading content and History API for navigation.

I want non-hashed urls. I'm manually adding url params on search which look this way

/?query=myQuery

Lets say the URL was currently /?q=firstQuery and the user changes it to /?q=secondQuery by himself in address bar.

I want to be able to detect the URL change and get the query value from params and fetch the results.

I've tried using

  1. popState event listeners - only detect back and forward button changes
  2. timeOut function to detect url changes - didn't detect the manual entries

I can see that the browser loads when URL is manually entered and the browser console gets cleared as well.

Is there a way to detect that change? - $(document).ready() , window.on('load') , beforeunload event listeners didn't work. There is only one index.html file that is loaded and the content is being manipulated in it.

I want it to be like [qwant.com](qwant.com) - pl suggest other methods to implement its behaviour in jQuery

1

There are 1 best solutions below

0
cSharp On

You can use the onbeforeunload event to look for the manual changes to the URL, but it is not a very reliable method as laid out in the MDN document.

window.onbeforeunload = function() {
  const currentUrl = location.pathname;
  if (currentUrl !== '/') {
    loadPage(currentUrl);
    return 'Are you sure you want to leave this page?';
  }
}

You're better off using a router library written by someone else, which will handle all the routing problems by itself.