所以我有一些代码在某种程度上起作用。
var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var sanitized = url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
url = 'https://' + sanitized;
window.onload = function urlChange(){
location.replace(url);
}
唯一的问题是,一旦url被更改,页面就会继续重新加载,就好像我有一个无限循环一样。
有什么想法吗?
谢谢!
答案 0 :(得分:1)
您需要检查网址是否实际更改,并且仅更改其位置(如果已更改)。您也应该使用window.url
而不是从协议,主机和路径名手动构建它。
var sanitized = window.url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
sanitized = 'https://' + sanitized; // add https to the front
window.onload = function urlChange() {
if (window.url !== sanitized) {
location.replace(sanitized);
}
}
答案 1 :(得分:0)
要更新网址而不实际更新location
(导致重新加载浏览器),您可以使用html5 pushState事件:
var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var sanitized = url
.replace(/^https\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
url = 'https://' + sanitized;
window.onload = function urlChange(){
window.history.pushState("object or string", "Title", url);
}