Is there any way I can modify the URL of the current page without reloading the page?
I would like to access the portion before the # hash if possible.
I only need to change the portion after the domain, so its not like I'm violating cross-domain policies.
window.location.href = "www.mysite.com/page2.php"; // sadly this reloads
转载于:https://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page
This can now be done in Chrome, Safari, FF4+, and IE10pp4+!
See this question's answer for more info: 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.
NOTE: If you are working with an HTML5
browser then you should ignore this answer. This is now possible as can be seen in the other answers.
There is no way to modify the URL
in the browser without reloading the page. The URL represents what the last loaded page was. If you change it (document.location
) then it will reload the page.
One obvious reason being, you write a site on www.mysite.com
that looks like a bank login page. Then you change the browser url bar to say www.mybank.com
. The user will be totally unaware that they are really looking at www.mysite.com
.
Any changes of the loction (either window.location
or document.location
) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.
Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.
Assuming you're not trying to do something malicious, anything you'd like to do to your own URLs can be magicked into being with htaccess.
parent.location.hash = "hello";
You can add anchor tags. I use this on my site http://www.piano-chords.net/ so that I can track with google analytics what people are visiting on the page. I just add an anchor tag and then the part of the page I want to track.
var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);
HTML5 introduced the history.pushState()
and history.replaceState()
methods, which allow you to add and modify history entries, respectively.
window.history.pushState('page2', 'Title', '/page2.php');
Read more about this from here
If what you're trying to do is allow users to bookmark/share pages, and you don't need it to be exactly the right URL, and you're not using hash anchors for anything else, then you can do this in two parts; you use the location.hash discussed above, and then implement a check on the home page, to look for a URL with a hash anchor in it, and redirect you to the subsequent result.
For instance:
1) User is on www.site.com/section/page/4
2) User does some action which changes the URL to www.site.com/#/section/page/6
(with the hash). Say you've loaded the correct content for page 6 into the page, so apart from the hash the user is not too disturbed.
3) User passes this URL on to someone else, or bookmarks it
4) Someone else, or the same user at a later date, goes to www.site.com/#/section/page/6
5) Code on www.site.com/
redirects the user to www.site.com/section/page/6
, using something like this:
if (window.location.hash.length > 0){
window.location = window.location.hash.substring(1);
}
Hope that makes sense! It's a useful approach for some situations.
It's possible without using hashes, have a look to the asual jQuery Address plugin:
Example here.
Note that it will use hashes in IE, there is no workaround for it.
You can also use HTML5 replaceState if you want to change the url but don't want to add the entry to the browser history:
if (window.history.replaceState) {
//prevents browser from storing history with each change:
window.history.replaceState(statedata, title, url);
}
This would 'break' the back button functionality. This may be required in some instances such as an image gallery (where you want the back button to return back to the gallery index page instead of moving back through each and every image you viewed) whilst giving each image its own unique url.
The HTML5 replaceState is the answer, as already mentioned by Vivart and geo1701. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.
As pointed out by Thomas Stjernegaard Jeppesen, you could use History.js to modify URL parameters whilst the user navigates through your Ajax links and apps.
Almost an year has passed since that answer, and History.js grew and became more stable and cross-browser. Now it can be used to manage history states in HTML5-compliant as well as in many HTML4-only browsers. In this demo You can see an example of how it works (as well as being able to try its functionalities and limits.
Should you need any help in how to use and implement this library, i suggest you to take a look at the source code of the demo page: you will see it's very easy to do.
Finally, for a comprehensive explanation of what can be the issues about using hashes (and hashbangs), check out this link by Benjamin Lupton.
Before HTML5 we can use:
parent.location.hash = "hello";
and:
window.location.replace("http:www.example.com");
This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url)
that should not reload your page.
Here is my solution: (newUrl is your new url which you want to replace current one)
history.pushState({}, null, newUrl);
Use history.pushState()
from HTML 5 History API
refer link for more details HTML5 History API
Below is the function to change the URL without reloading the page. It only support for HTML5
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = {Page: page, Url: url};
history.pushState(obj, obj.Page, obj.Url);
} else {
window.location.href = "homePage";
// alert("Browser does not support HTML5.");
}
}
ChangeUrl('Page1', 'homePage');
In modern browsers and HTML5, there is a method called pushState
on window history
. That will change the URL and push it to the history without loading the page.
You can use it like this, it will take 3 parameters, 1) state object 2) title and a URL):
window.history.pushState({page: "another"}, "another page", "example.html");
This will change the url, but not reload the page, also doesn't check if the page exist, so if you do some javascript code which be reacting to the URL, you can work with them like this.
Also there is history.replaceState()
which does exactly the same thing, except it will modify the current history instead of creating a new one!
Also you can create a function to check if history.pushState exist, then carry on with the rest like this:
function goTo(page, title, url) {
if ("undefined" !== typeof history.pushState) {
history.pushState({page: page}, title, url);
} else {
window.location.assign(url);
}
}
goTo("another page", "example", 'example.html');
Also you can change the #
for <HTML5 browsers
, which won't reload the page, that's the way Angular
use to do SPA
according to hashtag...
Changing #
is quite easy, doing like:
window.location.hash = "example";
and you can detect it like this:
window.onhashchange = function () {
console.log("#changed", window.location.hash);
}
Use window.history.pushState("object or string", "Title", "/new-url")
, but it's still send new url request to server
let stateObject = { foo: "bar" };
history.pushState(stateObject, "page 2", "newpage.html");
You can see here Update URL of browser without page reload