TL; DR
1-要修改当前URL并将其(新修改的URL)添加/注入为历史列表中的新URL条目,请使用:pushState
window.history.pushState({}, document.title, "/" + "my-new-url.html");
2-要替换当前网址而不将其添加到历史记录条目中,请使用replaceState:
window.history.replaceState({}, document.title, "/" + "my-new-url.html");
3- 根据您的业务逻辑,pushState在以下情况下将很有用:
从您的评论中可以了解到,您希望清除URL而无需再次重定向。
请注意,您无法更改整个URL。您可以更改域名后的名称。这意味着您无法更改,www.example.com/但可以更改之后的内容.com/
www.example.com/old-page-name => can become => www.example.com/myNewPaage20180322.php
背景
我们可以用:
1- 如果要向历史记录条目添加新的修改的URL,则使用pushState()方法。
2- 如果要更新/替换当前历史记录条目,则使用replaceState()方法。
.replaceState().pushState()除了.replaceState() 修改当前的历史记录条目而不是创建新的历史记录条目之外,其操作方式完全相同。请注意,这不会阻止在全局浏览器历史记录中创建新条目。
.replaceState()当您要响应某些用户操作而更新状态对象或当前历史记录条目的URL时,此功能特别有用。
码
为此,我将在本示例中使用pushState()方法,该方法的工作方式与以下格式类似:
var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );
随意更换pushState与replaceState根据您的要求。
您可以替换放慢参数"object or string"与{}和"Title"与document.title因此最终statment将变为:
window.history.pushState({}, document.title, "/" + myNewURL );
结果
前两行代码将创建一个URL,例如:
https://domain.tld/some/randome/url/which/will/be/deleted/
成为:
https://domain.tld/my-new-url.php
行动
现在让我们尝试另一种方法。假设您需要保留文件名。文件名位于最后一个/查询字符串之后?。
http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john
将会:
http://www.someDomain.com/keepThisLastOne.php
这样的事情将使其工作:
//fetch new URL
//refineURL() gives you the freedom to alter the URL string based on your needs.
var myNewURL = refineURL();
//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced.
window.history.pushState("object or string", "Title", "/" + myNewURL );
//Helper function to extract the URL between the last '/' and before '?'
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php'
//pseudo code: edit to match your URL settings
function refineURL()
{
//get full URL
var currURL= window.location.href; //get current address
//Get the URL between what's after '/' and befor '?'
//1- get URL after'/'
var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
//2- get the part before '?'
var beforeQueryString= afterDomain.split("?")[0];
return beforeQueryString;
}
更新:
对于一名班轮迷,请在您的控制台/萤火虫中尝试一下,此页面URL将会更改:
window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);
此页面的网址将更改为:
http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103
至
http://stackoverflow.com/22753103#22753103
注意:正如Samuel Liew在下面的注释中指出的,此功能仅针对引入HTML5。
另一种方法是实际重定向页面(但是您将丢失查询字符串'?',是否仍需要它或数据已被处理?)。
window.location.href = window.location.href.split("?")[0]; //"http://www.newurl.com";