How can I change the current URL?

Javascript

Javascript Problem Overview


I have the following code that changes the pages from within JavaScript:

var newUrl = [some code to build up URL string];
window.location.replace(newUrl);

But it doesn't change the top URL, so when someone clicks the back button it doesn't go back to the previous page.

How can I have JavaScript change the top URL as well so the browser back button works.

Javascript Solutions


Solution 1 - Javascript

Solution 2 - Javascript

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

  1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

    $(window).bind("popstate", function(e) { alert("location changed"); });

    Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

Solution 3 - Javascript

If you just want to update the relative path you can also do

window.location.pathname = '/relative-link'

"http://domain.com" -> "http://domain.com/relative-link"

Solution 4 - Javascript

Hmm, I would use

window.location = 'http://localhost/index.html#?options=go_here';

I'm not exactly sure if that is what you mean.

Solution 5 - Javascript

This will do it:

window.history.pushState(null,null,'https://www.google.com');

Solution 6 - Javascript

<script> 
	var url= "http://www.google.com"; 
	window.location = url; 
</script> 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - JavascriptglebmView Answer on Stackoverflow
Solution 2 - JavascriptbcherryView Answer on Stackoverflow
Solution 3 - JavascriptArtokunView Answer on Stackoverflow
Solution 4 - JavascriptBlenderView Answer on Stackoverflow
Solution 5 - JavascriptChris SmithView Answer on Stackoverflow
Solution 6 - Javascriptuser3230794View Answer on Stackoverflow