source

페이지를 새로 고치지 않고 JavaScript를 사용하여 window.location(URL)에서 해시를 삭제하려면 어떻게 해야 합니까?

manysource 2022. 11. 5. 17:38

페이지를 새로 고치지 않고 JavaScript를 사용하여 window.location(URL)에서 해시를 삭제하려면 어떻게 해야 합니까?

다음과 같은 URL이 있습니다.http://example.com#something, 삭제 방법#something페이지를 새로 고치지 않고?

다음 솔루션을 시도했습니다.

window.location.hash = '';

그러나 해시 기호는 제거되지 않습니다.#를 참조해 주세요.

오늘날에는 이 문제를 해결하는 것이 훨씬 더 손이 닿는 곳에 있다.HTML5 History API를 사용하면 현재 도메인 내의 URL을 표시하도록 위치 표시줄을 조작할 수 있습니다.

function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}

작업 데모: http://jsfiddle.net/AndyE/ycmPt/show/

이 기능은 Chrome 9, Firefox 4, Safari 5, Opera 11.50 및 IE 10에서 작동합니다.지원되지 않는 브라우저의 경우 언제든지 적절한 성능 저하 스크립트를 작성하여 사용할 수 있습니다.

function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

따라서 해시 기호를 제거할 수 있습니다.단, 일부 브라우저에서는 아직 삭제되지 않았습니다.

참고: 브라우저 기록의 현재 페이지를 바꾸려면replaceState()대신pushState().

첫 번째 질문:

window.location.href.substr(0, window.location.href.indexOf('#'))

또는

window.location.href.split('#')[0]

둘 다 해시 등의 URL을 반환하지 않습니다.

편집에 대해서:

변경 사항window.location페이지 새로 고침을 트리거합니다.변경할 수 있습니다.window.location.hash새로 고침을 트리거하지 않고(해시가 페이지의 ID와 일치하면 창이 점프하지만) 해시 기호를 제거할 수 없습니다.어느 쪽이 더 나쁜지 골라봐

최신 답변

희생하지 않고(완전 새로고침 또는 해시 부호를 그대로 두거나) 실행하는 방법에 대한 정답은 여기에 나와 있습니다.이 답변은 2009년 원본과 관련하여 남겨둔 반면, 새로운 브라우저 API를 활용하는 올바른 답변은 1.5년 후에 제공되었습니다.

(너무 많은 답변이 중복되어 오래되었습니다.)현재 최선의 해결책은 다음과 같습니다.

history.replaceState(null, null, ' ');

심플하고 우아함:

history.replaceState({}, document.title, ".");  // replace / with . to keep url

다음과 같이 할 수 있습니다.

history.replaceState({}, document.title, window.location.href.split('#')[0]);

해시를 제거하려면 이 함수를 사용해 보십시오.

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

이렇게 하면 후행 해시도 제거됩니다.예: http://test.com/123#abc -> http://test.com/123

if(window.history.pushState) {
    window.history.pushState('', '/', window.location.pathname)
} else {
    window.location.hash = '';
}

아래는 어떻습니까?

window.location.hash=' '

는 해시를 빈 문자열이 아닌 단일 공백으로 설정하고 있습니다.


해시를 비활성 앵커로 설정해도 새로 고침되지 않습니다.예를 들어,

window.location.hash='invalidtag'

하지만 위의 해법은 오해를 불러일으킬 수 있습니다.이것은 주어진 위치에 주어진 이름을 가진 앵커가 없다는 것을 나타내는 것 같습니다.동시에 빈 문자열을 사용하면 페이지가 맨 위로 이동하며 이는 허용되지 않을 수 있습니다.또한 공간을 사용하면 URL이 복사 및 북마크되고 다시 방문될 때마다 페이지가 항상 맨 위에 표시되며 공간은 무시됩니다.

Stack Overflow에 대한 첫 번째 답변입니다.누군가가 그것이 유용하고 지역사회의 기준에 부합하는 것을 발견하기를 바란다.

const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

window.addEventListener("load", function(){
    removeLocationHash();
});
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    window.history.replaceState({}, document.title, clean_uri);
}
</script>

이 코드를 헤드섹션에 입력하다

제 생각엔 그게 더 안전할 것 같아요.

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}
$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});

다음을 시도해 보십시오.

window.history.back(1);

다음은 href를 사용하여 위치를 변경하고 스크롤하지 않고 해시를 클리어하는 다른 솔루션입니다.

여기에 마법의 솔루션이 설명되어 있습니다.사양은 이쪽.

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

메모: 제안된 API는 WhatWG HTML Living Standard의 일부가 되었습니다.

위의 답변 중 하나를 바탕으로 다음을 사용합니다.

var scrollV, scrollH
var loc = window.location;
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
if ("pushState" in history) {
    history.pushState("", document.title, loc.pathname + loc.search);

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;

} else {
    loc.hash = "";

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;
}

해시를 null로 바꿀 수 있습니다.

var urlWithoutHash = document.location.href.replace(location.hash , "" );

언급URL : https://stackoverflow.com/questions/1397329/how-to-remove-the-hash-from-window-location-url-with-javascript-without-page-r