Programing

history.replaceState () 예제?

crosscheck 2020. 7. 16. 08:14
반응형

history.replaceState () 예제?


누구나 history.replaceState에 대한 실제 예제를 제공 할 수 있습니까? 이것이 w3.org가 말하는 것입니다 :

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

주어진 데이터, 제목 및 제공된 경우 (널이 아닌 경우) URL을 갖도록 세션 히스토리의 현재 항목을 업데이트합니다.

최신 정보:

이것은 완벽하게 작동합니다.

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

URL은 변경되지만 제목은 변경되지 않습니다. 버그입니까, 아니면 뭔가 빠졌습니까? 최신 Chrome에서 테스트되었습니다.


실제로 이것은 2 년 동안 의도적이지만 버그입니다. 문제는 불분명 한 스펙과 복잡 할 때 document.title와 뒤로 / 앞으로 의 복잡성 에 있습니다.

WebkitMozilla의 버그 참조를 참조하십시오 . 또한 히스토리 API 도입에 관한 오페라 는 타이틀 매개 변수를 사용 하지 않았으며 여전히 사용하지 않을 것이라고 말했다 .

현재 history 항목의 제목 인 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;


두 번째 인수 제목 은 페이지 제목을 의미하지 않습니다. 해당 페이지의 상태에 대한 정의 / 정보에 대한 것입니다

그러나 onpopstate 이벤트를 사용하여 제목을 변경하고 제목 이름을 두 번째 인수가 아닌 객체로 전달 된 첫 번째 매개 변수의 속성으로 전달할 수 있습니다

참조 : http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/


According to MDN History doc
There is clearly said that second argument is for future used not for now. You are right that second argument is deal with web-page title but currently it's ignored by all major browser.

Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.


I really wanted to respond to @Sev's answer.

Sev is right, there is a bug inside the window.history.replaceState

To fix this simply rewrite the constructor to set the title manually.

var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
    var title_ = document.getElementsByTagName('title')[0];
    if(title_ != undefined){
        title_.innerHTML = title;
    }else{
        var title__ = document.createElement('title');
        title__.innerHTML = title;
        var head_ = document.getElementsByTagName('head')[0];
        if(head_ != undefined){
            head_.appendChild(title__);
        }else{
            var head__ = document.createElement('head');
            document.documentElement.appendChild(head__);
            head__.appendChild(title__);
        }
    }
    replaceState_tmp(obj,title, url);
}

참고URL : https://stackoverflow.com/questions/12832317/history-replacestate-example

반응형