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

前端 未结 2 982
后悔当初
后悔当初 2021-01-29 12:55

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 i

相关标签:
2条回答
  • 2021-01-29 13:11

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

    0 讨论(0)
  • 2021-01-29 13:31

    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.

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