How to Change Url in Browser Without Navigating Away from Page

How to change URL in browser without navigating away from page?

You can do it with history.pushState, but only in browsers that support it. Just try the following line in your browsers JavaScript-Console.

history.pushState({},"URL Rewrite Example","https://stackoverflow.com/example")

More on that in The pushState() method (Mozilla Developer)

Similar question How do I, with JavaScript, change the URL in the browser without loading the new page?

How do I modify the URL without reloading the page?

This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!

See this question's answer for more information:
Updating address bar with new URL without hash or reloading the page

Example:

 function processAjaxData(response, urlPath){
document.getElementById("content").innerHTML = response.html;
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
}

You can then use window.onpopstate to detect the back/forward button navigation:

window.onpopstate = function(e){
if(e.state){
document.getElementById("content").innerHTML = e.state.html;
document.title = e.state.pageTitle;
}
};

For a more in-depth look at manipulating browser history, see this MDN article.

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');
  • More info (MDN article): Manipulating the browser history
  • Can I use
  • Maybe you should take a look @ Does Internet Explorer support pushState and replaceState?

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
// ...
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
// \o/
}

Prevent a webpage from navigating away using JavaScript

Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:

window.onbeforeunload = function() {
return "";
}

Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.

In older browsers you could specify the message to display in the prompt:

window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}

Change the URL in the browser without loading the new page using JavaScript

With HTML 5, use the history.pushState function. As an example:

<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>

and a href:

<a href="#" id='click'>Click to change url to bar.html</a>

If you want to change the URL without adding an entry to the back button list, use history.replaceState instead.

Change browser url without page reloading with ajax request

well, with my specific situation I had thousands of products organized in categories and sub categories. Well..thats a ton of urls and controllers to write. so what i did was make a category template, a sub category template and a product page template. then made routes like below in my application/config/routes.php file:

$route['products'] = 'products/index';

//so i know now they are on a category page and $1 is the name of the category.
//i can go query my db and get all subcategorys and the products under each now.
$route['products/(:any)'] = 'products/category/$1';

//the 1 and 2 here are category and subcategory from the url. so i know from this to
//use these in my query to grab all products in this category and subcategory.
$route['products/(:any)/(:any)'] = 'products/subcategory/$1/$2';

//i know this is gonna be a product page. and i know the category, the sub category and the product name. in this case all i really need is the product name since there is only one product with that name.
$route['products/(:any)/(:any)/(:any)'] = 'products/details/$1/$2/$3';

in your situation you can do the same. use your urls, your taking the time to build them so use them. in javascript you can send them back to your controllers via 'window.location.pathname'; all you have to do is split it up and you can use the same mentality to load a page and know exactly where you are at.

Also, in your ajax url property make sure your url is either an absolute url, or it references the root first. I think i know what your issue is. you are using a url like "users/dashboard" in your url property when it should be "/users/dashboard" you need to always go to the root and get the controller, otherwise it uses the url and will always take on the "users/dashboard" to the current url you are on. So if you are on "users/dashboard" and go load it again, your actually telling it to load "/users/dashboard/users/dashboard" and this becomes an infinite loop. Just put a backslash in front of your url and it will always reference the root.

Easiest way to open a download window without navigating away from the page

7 years have passed and
I don't know whether it works for IE6 or not, but this prompts OpenFileDialog in FF and Chrome.

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);


Related Topics



Leave a reply



Submit