简体   繁体   English

并非总是触发onpopstate

[英]onpopstate isn't always triggered

I have an angular project where im trying to capture the back button event, to trigger my own function. 我有一个角度项目,我试图捕获后退按钮事件,以触发我自己的功能。

I'm using onpopstate , from window ( js ) and platformLocation ( angular ), and the function isn't always triggered. 我正在使用onpopstate ,它来自windowjs )和platformLocationangular ),并且该函数并不总是被触发。

I have a login which redirects to my pages, and i can pass in two ways. 我有一个重定向到我的页面的登录名,并且我可以通过两种方式进行传递。

  • As a new user, in the register form in my app. 作为新用户,在我的应用程序中的注册表格中。 In this case the function is triggered 在这种情况下,功能被触发
  • Access with an existing account, to any page. 使用现有帐户访问任何页面。 In this case is where the function never works. 在这种情况下,该功能将永远无法使用。 In fact, if I go to the register page, it doesn't work neither. 实际上,如果我转到注册页面,那也不行。

I tried with window.onbeforeunload too, and always execute it, but when I try to redirect to another page (is what I want to do) and prevent the default navigation, isn't working. 我也尝试过window.onbeforeunload ,并且始终执行它,但是当我尝试重定向到另一个页面(这是我想做的)并阻止默认导航时,则无法正常工作。

Do you have some idea about what is happening? 您对正在发生的事情有什么了解吗?

I appreciate your help 我感谢您的帮助

EDIT 编辑

This is the main code in my service. 这是我服务中的主要代码。

Service code 服务代码

@Injectable()
export class BackService {

    constructor(
        private _platformLocation: PlatformLocation
    ) {
        vm.setBackEvent();
    }

    /**
     * NAvigation from browser
     */
    setBackEvent() {
        const vm = this;
        // JS ** this trigger the function but dont navigate
        // window.onbeforeunload = function (e) {
        //     console.log('onbbeforeunload');
        //     location.href = url;
        //     return ;
        // };

        // JS  ** this doesnt work always
        // window.onpopstate = (e) => {
        //     console.log('window onpopstate');
        //     location.href = url;
        // }


        // Angular ** his doesnt work always
        this._platformLocation.onPopState = (e: LocationChangeListener) => {
             console.log('PlatformLocation onpopstate');
             location.href = url;
        }
    }
}

I respond myself 我回应自己

i found this hack to trigger the popstate function always. 我发现此黑客总是触发popstate函数。

window.onpopstate = function (e) {
   // ... Some code ... 
}
history.pushState({}, ''); // this makes the function always works

thanks anyway 不管怎么说,还是要谢谢你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM