반응형

모바일 웹에서 뒤로가기 버튼 선택시 history.pushstate 사용해서 뒤로가기 이벤트 확인하기

 

모바일 웹에서 뒤로가기 버튼을 처리하려면 JavaScript를 사용하여 history.pushState를 활용할 수 있습니다. popstate 이벤트를 사용하여 뒤로가기 버튼의 클릭을 감지할 수 있습니다. 아래는 간단한 예제 코드입니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>뒤로가기 이벤트 확인</title>
</head>
<body>
    <h1>뒤로가기 이벤트 확인</h1>

    <script>
        // 현재 상태 저장
        history.pushState({ page: 1 }, "Title 1", "?page=1");

        // 뒤로가기 이벤트 처리
        window.addEventListener('popstate', function(event) {
            // event.state에는 현재 상태의 데이터가 들어있습니다.
            if (event.state) {
                alert('뒤로가기 버튼이 눌렸습니다. 페이지 상태: ' + JSON.stringify(event.state));
            } else {
                // 더 이상 뒤로 갈 수 없을 때, 예를 들어 초기 페이지에서 뒤로가기 버튼을 눌렀을 때 처리할 내용을 여기에 추가할 수 있습니다.
                alert('뒤로 갈 수 없습니다.');
            }
        });

        // 새로운 상태 추가 및 주소 변경
        function changeState() {
            const newState = { page: 2 };
            history.pushState(newState, "Title 2", "?page=2");
        }
    </script>

    <!-- 버튼을 클릭하여 상태를 변경하고 뒤로가기 이벤트를 확인할 수 있습니다. -->
    <button onclick="changeState()">새로운 상태로 이동</button>
</body>
</html>
반응형
반응형

History API (https://developer.mozilla.org/ko/docs/Web/API/History_API)

DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. history는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는, 유용한 메서드와 속성을 가집니다.

 

History.pushState  페이지 이동 없이 주소만 바꿔준다. (브라우저의 뒤로가가 버튼이 활성화 된다.)

브라우저 페이지를 이동하게 되면 window.onpopstate 라는 이벤트가 발생하게 되는데, pushState  했을때는 popstate 이벤트가 발생하지않고,  / 앞으로 가기를 클릭 했을때 popstate 이벤트가 발생하게 된다.

즉, pushState 와 popstate 둘을 이용하여 SPA 의 페이지 전환을 구현할 수 있다.

 

기본 형태 - history.pushState(state, title, url);

State : 브라우저 이동  넘겨줄 데이터 (popstate 에서 받아서 원하는 처리를 해줄  있음)

Title : 변경할 브라우저 제목 (변경 원치 않으면 null)

Url : 변경할 주소

 

사용예)

window.onpopstate = function(e) { 
    console.log(`${JSON.stringify(e.state)} | ${location.origin} | ${location.pathname}`);
}

var state = {page_id : 1, data : 'test'};
var url = location.origin + '/myPage';
history.pushState(state, null, url);

 코드를 실행하면 history.pushState  수행했을때 브라우저 주소에 /myPage  붙는걸   있고,

뒤로가기를(원래 url) 한뒤 다시 앞으로(pushState 추가된 url) 가기를 클릭 하면

콘솔 출력값으로 {"page_id":1,"data":"test"} | http://localhost:5000 | /myPage  출력된다.

 

 

* https://kwangsunny.tistory.com/28

반응형
반응형

[javascript] 새로고침 없이 파라미터 제거/수정

 

Remove URL parameters without refreshing page

window.history.pushState({}, document.title, "/" + myNewURL );

https://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page

 

Remove URL parameters without refreshing page

I am trying to remove everything after the "?" in the browser url on document ready. Here is what I am trying: jQuery(document).ready(function($) { var url = window.location.href; url = url...

stackoverflow.com

 

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState()

 

For one liner fans, try this out in your console/firebug and this page URL will change:

window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

 

History: pushState() method
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

 

History: pushState() method - Web APIs | MDN

In an HTML document, the history.pushState() method adds an entry to the browser's session history stack.

developer.mozilla.org

 

History.replaceState() https://developer.mozilla.org/ko/docs/Web/API/History/replaceState

 

History.replaceState() - Web API | MDN

History.replaceState() 메서드는 현재 history를 수정해 메소드의 매개 변수에 전달 된 stateObj, title, URL로 대체합니다. 이 방법은 특히 일부 유저의 동작에 대한 응답으로 history 객체의 상태나 현재 history

developer.mozilla.org

 

반응형
반응형

[javascript] 자바스크립트를 사용하여 현재 페이지를 새로고침, 갱신하지 않으면서 다른 주소로 변경하는 방법

 

History: pushState()

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

 

History: pushState() method - Web APIs | MDN

In an HTML document, the history.pushState() method adds an entry to the browser's session history stack.

developer.mozilla.org

history.pushstate(state, title, url)

state = 상태 값을 나타내는 것으로 브라우저에서 앞/ 뒤로 갈 때, 넘겨줄 데이터

title = 변경할 브라우저 제목 (변경을 원하지 않으면 null

url = 변경할 브라우저 URL

 

const state = { page_id: 1, user_id: 5 };
const url = "hello-world.html";

history.pushState(state, "", url);



const url = new URL(location);
url.searchParams.set("foo", "bar");
history.pushState({}, "", url);

검색 페이지나 페이지네이션(pagination)을 가진 페이지에서 많이 사용됩니다. 즉 검색 조건이나 페이지 전환이 비동기식 ajax로 이루어질때 이를 반영하기 위해 페이지 주소를 함께 변경하는 것입니다. 페이지 주소를 변경해두면 만약 페이지를 리로드, 갱신하더라도 바뀐 주소나 쿼리 스트링 정보를 그대로 가져올 수 있기 때문이죠.

pushstate()의 장점은 페이지 주소만 변경하는 것이 아니라 url 주소를 바꾸면서 동시에 데이터(state)를 전달하거나 타이틀 변경도 가능하다는 점입니다.

  • 데이터 state 값 전달 가능
  • 페이지 타이틀 변경

 

window.onpopstate = function(event) {
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
}

브라우저에서 뒤/앞으로 가는 버튼 클릭 시 onpopstate 이벤트가 발생하며 이때, 콜백함수에서 event.state는 pushState 함수의 인자 값이였던 state 객체가 넘어온 것이다.

 

onhashchange를 이용할 수도 있다. 

반응형

+ Recent posts