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

后端 未结 4 1294
温柔的废话
温柔的废话 2020-12-01 13:31

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

相关标签:
4条回答
  • 2020-12-01 13:41

    No, it's not possible. And, whenever it is possible, that is a browser bug (I know about previous security bugs related to this behavior, and they were fixed in past).

    Actually... You can change the last portion of the URL, anything after the # character. But the hostname and path can't be changed without leaving the page.

    0 讨论(0)
  • 2020-12-01 13:42

    You can change anything after the hash mark (#) as this is frequently used in Ajax applications such as Google search and the new Twitter. (That's why everything appears after the hash mark in those apps.) But if you change anything else, the page will have to be reloaded.

    0 讨论(0)
  • 2020-12-01 13:51

    I'm going to assume you are talking about the visible URL in the URL bar.

    The answer is No, it is a major security vulnerability when an application tries trick users into thinking that are at another site.

    0 讨论(0)
  • 2020-12-01 13:58

    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 .

    0 讨论(0)
提交回复
热议问题