javascript tutorial - [Solved-5 Solutions] Modify the URL without reloding the page - javascript - java script - javascript array
Problem:
Here's the most cross-browser solution.
This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.
if (!Object.keys) {
Object.keys = function (obj) {
var arr = [],
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
};
}
Object.keys(obj).length;
click below button to copy the code. By JavaScript tutorial team
Solution 1:
This can now be done in Chrome, Safari, FF4+, and IE10pp4+! 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);
}
click below button to copy the code. By JavaScript tutorial team
We 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;
}
};
click below button to copy the code. By JavaScript tutorial team
Solution 2:
HTML5 introduced the history.pushState()
and history.replaceState()
methods, which allow we to add and modify history entries, respectively.
window.history.pushState('page2', 'Title', '/page2.php');
click below button to copy the code. By JavaScript tutorial team
Solution 3:
We can also use HTML5 replaceState
if we 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);
}
click below button to copy the code. By JavaScript tutorial team
This would 'break' the back button functionality. This may be required in some instances such as an image gallery (where we want the back button to return back to the gallery index page instead of moving back through each and every image we viewed) whilst giving each image its own unique url.
Solution 4:
parent.location.hash = "hello";
click below button to copy the code. By JavaScript tutorial team
Solution 5:
Here is my solution: (newUrl is our new url which we want to replace current one)
history.pushState({}, null, newUrl);