Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - How to change the URL displayed in the browser without leaving the page

Is it possible with JavaScript to change the browser's URL, but not leave the page?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In older browsers, you can not change the url in the address bar without leaving the page. But you can change the hash portion of the url without leaving the page. That is to say you can change www.example.com to www.example.com#new_text with JavaScript window.location.hash = "new_text"; everything after the # can be changed.

However, in HTML5 there is a new History API which allows you to change the part of the URL after the domain. So you still cannot change www.example.com to www.BankOfAmerica.com (for security reasons), but you can change www.example.com/foo to www.example.com/bar.

history.pushState("object or string representing the state of the page", "new title", "newURL");

Check When can I use... to see which browsers support HTML5 session history management and support the new pushState method.

In addition there is a JavaScript library which will normalizes the history API across browsers and changes the URL in new browsers and uses the hash portion for old browsers. See history.js .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...