Explain Codes LogoExplain Codes Logo

How to get the browser to navigate to URL in JavaScript

javascript
navigation
window-location
client-side-routing
Alex KataevbyAlex Kataev·Aug 20, 2024
TLDR

The quick solution, ladies and gentlemen! Use window.location.href:

// Onwards to our fine example.com domain! window.location.href = 'https://www.example.com';

This one-liner directly sets the browser's current location to the specified URL - just like a magician's wand - triggering navigation.

Explanation: An in-depth look

Here's the run-down on different navigation patterns. You have three different tools at your disposal. It's like picking the right key for the right lock.

Seamless transition? Use window.location.replace!

The internet equivalent of stepping through a magic portal:

// Did you just step into another website or was it always this way? window.location.replace('https://www.new-destination.com');

Or keep a record with window.location.assign

Let's say you want to plant your flag into the internet history landscape:

// We were here, and we want it written into internet memory! window.location.assign('https://www.next-stop.com');

When to use which method: strategy time!

Want to leave breadcrumbs? window.location.href or window.location.assign

Best in scenarios when you aim to allow your users to return to their previous location:

  • Visiting external links: Keep a history record for back-navigation.
  • Moving within the same web application: Keep the navigation history for user reference.

Just want a get-out-of-jail card? window.location.replace

Perfectly suitable for situations like:

  • Redirecting after successful form submissions: No need for your users to "go back" to a completed form.
  • Login pages: Once users have logged in, they shouldn't be able to hit the back button to the login page.

Cross-browser compatibility: friends not foes

Make sure to use navigation methods that effectively work across different browsers. Consistency is key:

  • Stay future-proof: Opt for methods that aren't on the deprecation block.
  • Beware of varying behaviour across browsers: Test your methods in different browsers to ensure no user is left behind.

Security matters: armed and protected

As they say: "with great power comes great responsibility", be careful with redirection:

  • Make sure to validate the URL you're using to prevent phishing attacks.
  • It's best to use trusted source URLs and not untrusted user input - unless you like random surprises.

The challenge: Advanced tactics and tips

Reshaping the browser history footprint

You can also change the URL without the nasty page refresh, making it ideal for Single Page Applications navigations:

//Knock-knock! Who's there? A new path! history.pushState(null, '', '/new-path');
//Replace your current URL as easily as changing socks history.replaceState(null, '', '/replace-path');

Customizing user confirmation prompts

Here is how to manage unsaved changes before navigation using the good ol' beforeunload event:

// Are you sure you want to leave? You might be leaving behind some unsaved magic spells! window.addEventListener('beforeunload', function (e) { e.returnValue = 'Unsaved changes. Are you sure you want to leave?'; });

Taking advantage of client-side routing

Modern frameworks like React or Angular provide more sophisticated navigation controls with no full page loads:

  • React: useHistory hook from react-router-dom.
  • Angular: Router service.