It’s while developing the chrome extensions, I faced an issue while performing certain event on the page URL was getting updated but my script didn’t get executed (script executed once only on window onload event), you might also encounter similar use-case or might be your use-case could be different but our goal is same to detect the changes of the URL,

Example:

http://example.com

http://example.com/page1

http://example.com/page2

Let’s get started

There is no clear, event-based way to detect URL changes directly, but there is a different way to overcome this.

What we need is to store the current URL when the page loads and then check the URL every n milliseconds for changes using setInterval (The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds)) so this will execute continuously, we will check the URL against the original stored URL, this way our use-case gets resolved

The following code does this check twice a second (500ms)

// Store the current page URL on load
var currentPage = location.href;

// listen for changes
setInterval(function()
{
    if (currentPage != location.href)
    {
        // page has changed, set new page as 'current'
        currentPage = location.href;

        // your custom code here
    }
}, 500);

There you have it 🙂

Read More on Web Development

Is there any other way to do it? Please share it in the comments section!


2 Comments

Abdul · April 29, 2022 at 9:51 pm

It isn’t work :/.

    Amit K Khanchandani · July 7, 2022 at 8:34 pm

    This works for Single Page Application. Incase you have the separate files, this may not work for you in such case.

Leave a Reply

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