How can I remove the query string from the url after the page loads?

前端 未结 10 1064
栀梦
栀梦 2020-12-16 10:03

I have a URL with a long query string attached to it. After the page loads, I do not require the query string. So I want to remove the query string from the address bar with

相关标签:
10条回答
  • As others have said, you can do this using the History API in modern browsers (IE10+, FF4+, Chrome5+). There was no full example in the answers, so figured I'd share my solution, as I just had a requirement to do the same thing:

    history.pushState(null, "", location.href.split("?")[0]);
    

    If you are using Modernizr, you can also check if the History API is available like so:

    if (Modernizr.history) {
        history.pushState(null, "", location.href.split("?")[0]);
    }
    
    0 讨论(0)
  • 2020-12-16 10:22

    You can't do that without reloading the page, imagine if you could put whatever you wanted in the browser address bar? Security fun :)

    Although you can now do it in HTML5 (which will only work on browsers supporting it) using the new history API, but realistically, your scenario best warrants a rewrite instead of including that (seems sledgehammer to crack a nut).

    As you said you don't need the query string after the page loads, you should really post back, then redirected to another URL after you've finished your processing.

    0 讨论(0)
  • 2020-12-16 10:22

    You could avoid a query string altogether by using POST instead of GET.

    0 讨论(0)
  • 2020-12-16 10:27

    Remove query string value from address bar

    var uri = window.location.toString();
    if (uri.indexOf("?") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("?"));
        window.history.replaceState({}, document.title, clean_uri);
    }
    
    0 讨论(0)
  • 2020-12-16 10:31

    window.history.replaceState(null, null, window.location.pathname);

    0 讨论(0)
  • 2020-12-16 10:33

    Use history.replaceState({}, "Title", "page.html");

    same syntax for pushState. However you will have to find a way to make IE understand that.

    A better way would be to use Apache mod_rewrite module. It's quite easy to use.

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