history.replaceState() 示例?

IT技术 javascript ajax html
2021-03-05 18:50:56

任何人都可以为 history.replaceState 提供一个工作示例吗?这是w3.org所说的:

history.replaceState(data, title [, url ] )

更新会话历史记录中的当前条目以具有给定的数据、标题和 URL(如果提供且不为空)。


更新

这完美地工作:

history.replaceState( {} , 'foo', '/foo' );

URL 在变,但标题没有变。这是一个错误还是我错过了什么?在最新的 Chrome 上测试。

6个回答

确实这是一个错误,尽管现在是故意的 2 年。问题在于一些不明确的规范以及document.title涉及到后退/前进的复杂性

请参阅WebkitMozilla上的错误参考此外,Opera 在介绍 History API 时表示它没有使用 title 参数,而且可能仍然没有使用。

目前,pushState 和replaceState 的第二个参数——历史条目的标题——没有在Opera 的实现中使用,但可能有一天会用到。

潜在的解决方案

我看到的唯一方法是更改​​标题元素并使用 pushState 代替:

document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );
对于 jquery 用户.. 试试 $("title").html(_title);
2021-04-21 18:50:56
这可能会导致用户需要“双击”后退按钮,具体取决于您的实现方式。一个更简单的解决方案可能是继续使用replaceState()并简单地手动设置文档标题document.title = "title"
2021-04-25 18:50:56

这是一个最小的、人为的例子。

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()但我不知道你到底想用它做什么。

url 正在更改,但标题未更改 .. 已使用最新的 chrome @trott 进行测试
2021-05-08 18:50:56
@Serjas 据我所知,title参数 inreplaceState()在所有浏览器中都被忽略。
2021-05-12 18:50:56

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));
@GiwrgosTsopanoglou:我在一年前回答过这个问题,所以我不确定为什么 :-P 无论如何,replaceState更改当前页面状态。它允许您更改当前页面状态的状态对象和 URL
2021-05-01 18:50:56
为什么接受的答案解释“pushState”而不是“replaceState”?
2021-05-10 18:50:56
奇怪的是,我正在寻找有关 replaceState 的信息,最终阅读了有关 pushState 的信息:P
2021-05-18 18:50:56

看例子

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/