programing

history.replaceState() 예?

nicescript 2023. 2. 15. 22:31
반응형

history.replaceState() 예?

누구나 이력의 실제 예를 들어줄 수 있습니까?replaceState?w3.org은 다음과 같이 기술하고 있습니다.

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

세션 이력 내의 현재 엔트리를 업데이트하여 지정된 데이터, 제목 및 URL(null이 아닌 경우)을 지정합니다.


갱신하다

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

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

URL은 변경되지만 제목은 변경되지 않습니다.그게 버그인가요 아니면 제가 뭘 놓치고 있는 건가요?최신 Chrome에서 테스트 완료.

2년 전부터 의도적이긴 하지만, 이것은 확실히 버그입니다.이 문제는 몇 가지 불명확한 사양과 복잡성에 있습니다.document.title및 백/포워드가 관련되어 있습니다.

Webkit Mozilla의 버그 레퍼런스를 참조해 주세요.또한 History API의 도입에 관한 Opera는 title 파라미터를 사용하지 않고 있으며 아마도 아직 사용하지 않을 이라고 말했다.

현재 pushState 및 replaceState의 두 번째 인수(이력 엔트리의 제목)는 Opera 구현에서는 사용되지 않지만 1일 수 있습니다.

잠재적인 솔루션

제목 요소를 변경하고 대신 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 사양은 초안일 뿐이며 브라우저에 따라 구현 방법이 다를 수 있습니다.예를 들어 Firefox는 다음 명령을 무시합니다.title파라미터가 완전합니다.

다음은 의 간단한 예입니다.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;

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

그러나 온팝스테이트이벤트를 사용하여 제목을 변경할 수 있습니다.또한 두 번째 인수가 아닌 오브젝트로 전달된 첫 번째 파라미터의 속성으로 제목명을 전달할 수도 있습니다.

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

MDN 이력 문서에 따라
두 번째 주장은 미래를 위한 것이지 지금은 사용되지 않는다는 것이 명백하다.두 번째 인수는 웹 페이지 제목에 관한 것이지만 현재 모든 주요 브라우저에서 무시되고 있습니다.

Firefox는 현재 이 파라미터를 무시하지만 향후 이 파라미터를 사용할 수도 있습니다.여기에 빈 문자열을 전달하면 메서드가 나중에 변경되지 않도록 안전합니다.또는 이동할 주에 대한 짧은 제목을 전달할 수도 있습니다.

@Sev의 답변에 꼭 답하고 싶었습니다.

요. 안에 버그가 있어요.window.history.replaceState

이 문제를 해결하려면 생성자를 다시 작성하여 제목을 수동으로 설정하십시오.

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);
}

https://www.mozilla.org/foo.html에서 다음 JavaScript가 실행된다고 가정합니다.

const stateObj = { foo: 'bar' };

history.pushState(stateObj, '', 'bar.html');

이로 인해 URL 바에 https://www.mozilla.org/bar2.html,이 표시되지만 브라우저에 bar2.120이 로드되거나 bar2.120이 존재하는지 확인하지 않습니다.

합니다.URL은 'URL'URL.http://localhost:4200/inspections/report-details/60c88e4e76b14c00193f5bef

let reportId = '60c88e4e76b14c00193f5bef', scope = "dynamic"

window.history.replaceState(null, null, `inspections/report-details/${reportId}?damagePart=` + scope );

하면 출력이 .http://localhost:4200/inspections/report-details/60c88e4e76b14c00193f5bef?damagePart=dynamic/

언급URL : https://stackoverflow.com/questions/12832317/history-replacestate-example

반응형