任何人都可以为 history.replaceState 提供一个工作示例吗?这是w3.org所说的:
history.replaceState(data, title [, url ] )
更新会话历史记录中的当前条目以具有给定的数据、标题和 URL(如果提供且不为空)。
更新
这完美地工作:
history.replaceState( {} , 'foo', '/foo' );
URL 在变,但标题没有变。这是一个错误还是我错过了什么?在最新的 Chrome 上测试。
任何人都可以为 history.replaceState 提供一个工作示例吗?这是w3.org所说的:
history.replaceState(data, title [, url ] )
更新会话历史记录中的当前条目以具有给定的数据、标题和 URL(如果提供且不为空)。
这完美地工作:
history.replaceState( {} , 'foo', '/foo' );
URL 在变,但标题没有变。这是一个错误还是我错过了什么?在最新的 Chrome 上测试。
确实这是一个错误,尽管现在是故意的 2 年。问题在于一些不明确的规范以及document.title
涉及到后退/前进的复杂性。
请参阅Webkit和Mozilla上的错误参考。此外,Opera 在介绍 History API 时表示它没有使用 title 参数,而且可能仍然没有使用。
目前,pushState 和replaceState 的第二个参数——历史条目的标题——没有在Opera 的实现中使用,但可能有一天会用到。
潜在的解决方案
我看到的唯一方法是更改标题元素并使用 pushState 代替:
document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );
这是一个最小的、人为的例子。
console.log( window.location.href ); // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href ); // oh, hey, it replaced the path with /foo
还有更多,replaceState()
但我不知道你到底想用它做什么。
history.pushState
将当前页面状态推送到历史堆栈,并更改地址栏中的 URL。因此,当您返回时,该状态(您传递的对象)将返回给您。
目前,这就是它所做的一切。任何其他页面操作,例如显示新页面或更改页面标题,都必须由您完成。
您链接的 W3C 规范只是一个草案,浏览器可能会以不同的方式实现它。 例如,Firefoxtitle
完全忽略该参数。
这是pushState
我在我的网站上使用的一个简单示例。
(function($){
// Use AJAX to load the page, and change the title
function loadPage(sel, p){
$(sel).load(p + ' #content', function(){
document.title = $('#pageData').data('title');
});
}
// When a link is clicked, use AJAX to load that page
// but use pushState to change the URL bar
$(document).on('click', 'a', function(e){
e.preventDefault();
history.pushState({page: this.href}, '', this.href);
loadPage('#frontPage', this.href);
});
// This event is triggered when you visit a page in the history
// like when yu push the "back" button
$(window).on('popstate', function(e){
loadPage('#frontPage', location.pathname);
console.log(e.originalEvent.state);
});
}(jQuery));
看例子
window.history.replaceState({
foo: 'bar'
}, 'Nice URL Title', '/nice_url');
window.onpopstate = function (e) {
if (typeof e.state == "object" && e.state.foo == "bar") {
alert("Blah blah blah");
}
};
window.history.go(-1);
和搜索location.hash
;
第二个参数Title并不意味着页面的标题 - 它更多的是该页面状态的定义/信息
但是我们仍然可以使用onpopstate事件更改标题,并且不是从第二个参数传递标题名称,而是作为作为对象传递的第一个参数的属性
参考:http : //spoiledmilk.com/blog/html5-changed-the-browser-url-without-refreshing-page/