software development, devops, and stuff
Tree lined path

Detect When the Browser URL Changes (JavaScript)

When building a single page web app it’s important to update the URLs without refreshing the page and so the user can easily copy and share or revisit the current page.

How Can This Be Done?

Fortunately the browser provides an API that works in such use cases. Enter “popstate event” this works hand and hand with the history.pushState() event which updates the URL. When the user clicks either the forward or back button the URL will change but unfortunately the page content will not.

Here’s an example of how to add a listener for when popstate fires.

window.addEventListener('popstate', function (event) {
	// Code here for URL change

Here’s a quick demo of it’s use when combined with the history.pushState() method.

Open demo in new tab