Requirement Description: When the modal box such as prompt box pops up on the H5 page, click route rollback (Android back key, etc.), but the modal box is not closed, but the route is rolled back. This method intercepts and throws an event when the rollback operation is detected for custom operation

Interceptor method encapsulation:

export function popstateListener(callback: Function) {
    history.pushState(null, "", location.href);
    let popstateFun = () => {
        window.removeEventListener("popstate", popstateFun);
    window.addEventListener("popstate", popstateFun);
Copy the code


popstateListener(() => {
     console.log("Intercepted return event, perform your own operation")})Copy the code

Improvement methods:

// This method must be removed if the current page is not the first view (including child routes shown), otherwise unknown errors will occurlet callbacks;
let hasListenersBack = false;
let listenersBackIdentifier;
function popstateFun() {
    window.removeEventListener("popstate", popstateFun);
    hasListenersBack = false; listenersBackIdentifier = null; } class PopstateHandler {// popstateListener(callback: Function, identifier? : string) {if(! hasListenersBack) { hasListenersBack =true;
            callbacks = callback;
            listenersBackIdentifier = identifier;
            history.pushState(null, "", location.href);
            window.addEventListener("popstate", popstateFun); } } removePopstateListener(identifier? : string) {// No identifiers are added when listening or can be removed as if they were added when listeningsetTimeout(() => {
            if((listenersBackIdentifier && listenersBackIdentifier === identifier) || ! identifier) { window.removeEventListener("popstate", popstateFun);
                hasListenersBack = false; listenersBackIdentifier = null; history.back() } }); }}export const popstateHandler = new PopstateHandler();

Copy the code

Prevent repeated registration of listening methods, and add identifier identifier. Only after the identifier registered last time is cleared, it can be registered again to prevent confusion caused by multiple interception in the page