如何在不离开页面的情况下更改浏览器中显示的URL [英] How to change the URL displayed in the browser without leaving the page
问题描述
用JavaScript可以更改浏览器的URL,但是不能离开页面吗?
Is it possible with JavaScript to change the browser's URL, but not leave the page?
推荐答案
在旧版浏览器中,你不可以在不离开页面的情况下更改地址栏中的网址。但是您可以在不离开页面的情况下更改URL的哈希部分。也就是说,您可以使用JavaScript <$将 www.example.com
更改为 www.example.com #new_text
c $ c> window.location.hash =new_text; #
之后的所有内容都可以更改。
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.
然而,在HTML5中有一个新的历史API,它允许您更改域后的URL部分。所以你仍然无法将 www.example.com
更改为 www.BankOfAmerica.com
(出于安全原因),但是你可以将 www.example.com/foo
更改为 www.example.com/bar
。
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");
检查我什么时候可以使用...... 查看哪些浏览器支持HTML5会话历史记录管理并支持新的 pushState
方法。
Check When can I use... to see which browsers support HTML5 session history management and support the new pushState
method.
此外,还有一个JavaScript库,可以跨浏览器规范化历史API,并在新浏览器中更改URL,并使用旧浏览器的哈希部分。请参阅 history.js 。
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 .
这篇关于如何在不离开页面的情况下更改浏览器中显示的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!