programing

Vuejs 'beforeunload' 이벤트가 예상대로 트리거되지 않음

randomtip 2022. 8. 30. 21:43
반응형

Vuejs 'beforeunload' 이벤트가 예상대로 트리거되지 않음

vue 라우터의 루트에서 사용하는 컴포넌트의 생성된 후크에 'before unload' 이벤트를 등록했습니다.

브라우저 탭 닫기 또는 브라우저 탭 새로 고침 또는 브라우저 닫기 사용자를 제거하기 위해 이 이벤트 핸들러를 호출합니다.

컴포넌트a

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}

컴포넌트 B에 대해 희미하게 설명

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}

그리고 내 라우터.js

{
  path: '/staff/call/:session_key',
  name: 'Staff Call',
  component: ComponentA,
  meta: {auth: true}
},
{
  path: '/consumer/call/:session_key',
  name: 'Consumer Call',
  component: ComponentB
},

여기서 '언로드 전' 이벤트 핸들러는 랜덤으로 트리거됩니다.그것은 때때로 유발되고 때로는 유발되지 않는 것이다.트리거될 때와 그렇지 않을 때 패턴을 찾습니다.

내가 뭘 놓쳤지?

편집
그렇다면 가장 유력한 범인은 @Patrick Steel이 말한 그대로일 것이다.MDN에서:

주의: 원치 않는 팝업을 방지하기 위해 일부 브라우저는 페이지가 상호 작용하지 않는 한 이벤트 핸들러에서 생성된 프롬프트를 표시하지 않으며 일부 브라우저는 해당 프롬프트를 전혀 표시하지 않습니다.특정 브라우저 목록은 Browser_compatibility 섹션을 참조하십시오.

페이지와 상호 작용하지 않는 경우가 있기 때문에 일관되지 않은 행동을 볼 수 있습니다.

구문 오류일 수 있습니다. created방법이 되어야 한다

created () {    
        window.addEventListener('beforeunload', this.removeUser)  
    },

    methods: {
      removeUser () {
        //remove user here
      }
    }

바이올린 작동: https://jsfiddle.net/e6m6t4kd/3/

새로고침 전 또는 vue.js에서 닫기 전에 작업을 수행합니다.

여기에 이미지 설명 입력

created() {
    window.onbeforeunload = function(){
           return "handle your events or msgs here";
    }
}

위의 예에 대해 약간의 조작을 해야 했습니다.이것이 가장 강력한 해결책이라고 생각합니다.

let app1 = new Vue({
    delimiters: ['[[', ']]'],       
    el: '#app',
    data: {
        dirty_form: true,
    },

    created () {
        console.log('created')
        window.addEventListener('beforeunload', this.confirm_leaving)
    },

    methods: {
        confirm_leaving (evt) {
            if (this.dirty_form) {
                const unsaved_changes_warning = "You have unsaved changes. Are you sure you wish to leave?";
                evt.returnValue = unsaved_changes_warning; 
                return unsaved_changes_warning;
            };
        };
    },
});

F5 또는 Ctrl + R을 누를 때마다 Vue에서 페이지 새로 고침/변경을 감지하려면 Navigation Timing API를 사용해야 할 수 있습니다.

PerformanceNavigation.type은 페이지에 액세스한 방법을 알려줍니다.

created() {
    // does the browser support the Navigation Timing API?
    if (window.performance) {
        console.info("window.performance is supported");
    }
    // do something based on the navigation type...
    if(performance.navigation.type === 1) {
        console.info("TYPE_RELOAD");
        this.removeUser();
    }
}

언급URL : https://stackoverflow.com/questions/49731080/vuejs-beforeunload-event-not-triggered-as-expected

반응형