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.

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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let lastUrl = location.href; new MutationObserver(() => { const url = location.href; if (url !== lastUrl) { lastUrl = url; onUrlChange(); } }).observe(document, {subtree: true, childList: true}); function onUrlChange() { alert('URL changed!', location.href); } |
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 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:
- How to Get HTML Tag Value in PHP
- How to Keep Value After Page Reload in PHP
- 2 Ways to Open URL in New Tab Using JavaScript
- How to Embed PDF in Website Using HTML
Happy Coding..!