How can I remove the query string from the url aft

2019-01-24 00:01发布

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 without a page reload.

I tried parent.location.hash = ''; and window.location.href = '/#'

They did not make a difference.

9条回答
Deceive 欺骗
2楼-- · 2019-01-24 00:44

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.

查看更多
不美不萌又怎样
3楼-- · 2019-01-24 00:44

I want to add one more way to do this, especially for the ones who are using $routeProvider.

As it has been mentioned in some other answers, you do this by using:

var yourCurrentUrl = window.location.href.split('?')[0]; 
window.history.replaceState({}, '', yourCurrentUrl ); 

or by creating a new record in history stack:

window.history.pushState({}, '', yourCurrentUrl );  

For a very detailed and nice explanation about doing with history.pushState and history.replaceState , you can read this post on SO .

HOWEVER if you are using Angular $routeProvider in your app, then it will still capture this change if that matches with any existing pattern. To avoid that, make sure your $routeProvider has reloadOnSearch flag set to false because by default it is true .

For example:

$routeProvider.when("/path/to/my/route",{
   controller: 'MyController',
   templateUrl: '/path/to/template.html',
   //Secret Sauce
   reloadOnSearch: false//Make sure this is explicitly set to false
});
查看更多
Root(大扎)
4楼-- · 2019-01-24 00:49

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]);
}
查看更多
登录 后发表回答