how to fully change url without reloading the page to new url?

谁都会走 提交于 2020-01-11 14:51:07

问题


I have gone through many questions asked here regarding changing url without reloading. Whilst I tried almost all of the methods, I am failed to fully change the url of a page including its domain name part without reloading the new page. How can I do that?


回答1:


That is not possible for a good reason. You can get more info about this here: Same-origin policy




回答2:


You can use pushState to do what you describe. As an example (pulled from here: https://www.aspsnippets.com/Articles/Change-URL-in-Browser-Address-Bar-without-reloading-using-JavaScript-and-jQuery.aspx)

<script type="text/javascript">
function ChangeUrl(title, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Title: title, Url: url };
        history.pushState(obj, obj.Title, obj.Url);
    } else {
        alert("Browser does not support HTML5.");
    }
}
</script>
<input type="button" value="Page1" onclick="ChangeUrl('Page1', 'Page1.htm');" />
<input type="button" value="Page2" onclick="ChangeUrl('Page2', 'Page2.htm');" />
<input type="button" value="Page3" onclick="ChangeUrl('Page3', 'Page3.htm');" />

Note that this will not work if you are trying to open a test file directly in your browser (i.e., if the URL will be file://whatever). The browser behaves differently. You will need to serve it via some http server.

Edit This doesn't answer the specific question asked by the OP. It will change the path, but you cannot change the hostname portion of a URL via pushState. As someone else already answered, it is not possible to change that without reloading the page due to the Same-origin policy. I left this here in case others just needed to change path portion of the URL.



来源:https://stackoverflow.com/questions/52119656/how-to-fully-change-url-without-reloading-the-page-to-new-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!