首页 > 解决方案 > 在Angular 7中处理浏览器主页按钮单击事件

问题描述

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

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

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

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

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);
           }
        });

请帮忙。

标签: angular7

解决方案


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

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

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


推荐阅读