在 Angular 7 中处理浏览器主页按钮单击事件

Handling Browser Home button click event in Angular 7

我正在使用 Angular 7 并努力获取浏览器主页按钮点击事件。

场景:- 当用户单击浏览器的主页按钮时,我需要向用户显示确认消息,询问用户是否要保存更改。如果 "Yes" 则用户将停留在当前页面,如果单击 "No" 则重定向到浏览器默认页面或可能路由到其他页面。

当我在 google 上搜索时,我得到的大部分链接都是针对浏览器后退按钮的,这在这种情况下没有帮助。

到目前为止,我已经尝试了以下解决方案,但它们无法正常工作,因为它无法捕获并保持刷新和主页按钮的处理程序。

1. 
        @HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) 
          {
            event.returnValue = false;
          }



    2. 

        //check for Navigation Timing API support
         if (window.performance) {
           console.info("window.performance works fine on this browser");
         }
         if (performance.navigation.type == 1) {
             confirm('This is performance Api');
             console.info( "This page is reloaded" );
         } else {
             console.info( "This page is not reloaded");
         }



    3. 
          this.router.events.subscribe((evt) => {
           if (evt instanceof NavigationEnd) {
               //trick the Router into believing it's last link wasn't previously loaded
              this.router.navigated = false;
              if (!this.router.navigated){
                 console.log(browserRefresh);
              }
               //if you need to scroll back to top, here is the right place
              window.scrollTo(0, 0);
           }
        });

请帮忙

恐怕您正在寻找的行为是不可能的。如果可以覆盖 beforeunload 默认行为(或类似行为),那么恶意网站可能会诱骗用户认为他们已经离开页面,而实际上他们并没有。

事实上,过去可以自定义显示的消息,但此功能已被删除(2016 年)以防止此类诈骗:

https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs