有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
有没有一种方法可以在不重新加载页面的情况下修改当前页面的URL?
如果可能,我想访问#哈希之前的部分。
我只需要更改域之后的部分,所以我不会违反跨域策略。
window.location.href = "www.mysite.com/page2.php"; // this reloads
当前回答
您的新url。
let newUrlIS = window.location.origin + '/user/profile/management';
在某种意义上,调用pushState()类似于设置window.location=“#foo”,因为两者都会创建并激活与当前文档相关的另一个历史条目。但是pushState()有一些优点:
history.pushState({}, null, newUrlIS);
您可以签出根目录:https://developer.mozilla.org/en-US/docs/Web/API/History_API
其他回答
位置的任何更改(window.location或document.location)都将导致对新URL的请求,如果您不仅仅是更改URL片段。如果更改URL,则更改URL。
如果您不喜欢当前使用的URL,请使用服务器端URL重写技术,如Apache的mod_rewrite。
如果您想更改url但不想将条目添加到浏览器历史记录中,也可以使用HTML5 replaceState:
if (window.history.replaceState) {
//prevents browser from storing history with each change:
window.history.replaceState(statedata, title, url);
}
这将“破坏”后退按钮功能。在某些情况下,这可能是必需的,例如图像库(您希望后退按钮返回到库索引页,而不是返回到您查看的每个图像),同时为每个图像提供自己的唯一url。
可以添加定位标记。我在我的网站上使用这个,这样我就可以通过Google Analytics跟踪人们在页面上访问的内容。
我只是添加了一个锚标记,然后添加了我要跟踪的页面部分:
var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);
在现代浏览器和HTML5中,有一种叫做pushState的窗口历史记录方法。这将更改URL并将其推送到历史记录中,而无需加载页面。
您可以这样使用它,它需要3个参数,1)状态对象2)标题和URL):
window.history.pushState({page: "another"}, "another page", "example.html");
这将更改URL,但不会重新加载页面。此外,它不会检查页面是否存在,因此如果您执行一些对URL做出反应的JavaScript代码,您可以这样处理它们。
此外,还有history.replaceState(),它做了完全相同的事情,只是它将修改当前历史,而不是创建新的历史!
此外,您还可以创建一个函数来检查history.pushState是否存在,然后执行以下操作:
function goTo(page, title, url) {
if ("undefined" !== typeof history.pushState) {
history.pushState({page: page}, title, url);
} else {
window.location.assign(url);
}
}
goTo("another page", "example", 'example.html');
此外,您可以更改<HTML5浏览器的#,这不会重新加载页面。这是Angular根据标签进行SPA的方法。。。
更改#非常简单,比如:
window.location.hash = "example";
你可以这样检测:
window.onhashchange = function () {
console.log("#changed", window.location.hash);
}
您可以在应用程序的任何位置使用这个美丽而简单的功能。
function changeurl(url, title) {
var new_url = '/' + url;
window.history.pushState('data', title, new_url);
}
您不仅可以编辑URL,还可以同时更新标题。