PHP Beginners

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...

Written by Bikash · 52 sec read >
Detect-URL-Change-in-JavaScript-Without-Refresh.png

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 need to know about MutationObserver() function.

Detect-URL-Change-in-JavaScript-Without-Refresh.png
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 single-page websites 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 methodobserve() 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 and then call the function which prompts with a 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..!

Was this article helpful?
YesNo
Written by Bikash
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP. Profile

Leave a Reply

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