Detect URL Change in JavaScript Without Refresh

To Detect URL Change in JavaScript Without Refresh we use MutationObserver() function. And JavaScript location.href functionality..

Before we go through the source code of Detect URL or DOM Change in JavaScript Without Refresh, first we know about MutationObserver() function.

Detect URL Change in JavaScript Without Refresh
How to Detect URL Change in JavaScript

What is MutationObserver() function

The MutationObserver() function is used to detect or watch the changes made on the DOM tree. It simply detects the DOM element changes and also URL changes on the single-page website like React JS and Angular JS.

Source Code to Detect URL Change in JavaScript Without Page Refresh

Code Explanations:

  • On the above source code first, we take the current URL of the page using location.href;
  • After that, we use the MutationObserver method observe() configures the MutationObserver callback to begin receiving notifications of changes to the DOM that match the given options.
    • observe(document, {subtree: true, childList: true});
  • At the last, we compare the URLs then call the function which prompts with new location URL.

You can copy the complete code as it is to check or use on your existing program.

To know more about the mutation Observer function you can check here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Also Check:

Happy Coding..!

Subscribe For Latest Updates

Sign up to best of PHP Code Solutions, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

Bikash

My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *