【问题标题】:ionic 4 prevent/disable device hardware backbuttonionic 4 防止/禁用设备硬件后退按钮
【发布时间】:2019-08-11 23:41:07
【问题描述】:

我正在使用 ionic 4 项目的角度路由(@angular/router)来禁用 ionic 4 中的设备后退按钮,防止默认不工作下面是我的代码

app.component.ts

    this.platform.backButton.subscribe(() => {
        if (this.router.url === '/Login') {
          this.util.presentAppExitAlert();
        } else {
          // event.preventDefault();
          console.log("invoing url ", this.router.url);
        }
      });
    });

我无法在此处禁用设备后退按钮的任何帮助

【问题讨论】:

    标签: angular typescript ionic-framework ionic4 angular-router


    【解决方案1】:
    initializeApp() {
        this.platform.ready().then(() => {
          this.platform.backButton.subscribeWithPriority(9999, () => {
            document.addEventListener('backbutton', function (event) {
              event.preventDefault();
              event.stopPropagation();
              console.log('hello');
            }, false);
          });
          this.statusBar.styleDefault();
        });
      }
    

    【讨论】:

    • 为我工作我正在使用 ionic 4.1 此代码必须进入 app-component.ts 并导入平台:)
    • 是否可以在加载时添加它并在加载结束时启用它?
    • 以及如何删除它?
    • 如何调整此代码以使后退按钮导致导航回登录屏幕?我尝试在您的 'hello' 行之后添加 this.router.navigate(['/login']) ,但收到错误:无法读取未定义的属性 'navigate'。我在构造函数中添加了私有路由器:路由器,但仍然是同样的错误。
    • 您的代码有效,但在技术上是错误的,每次有人按下后退按钮时,您都会添加一个事件侦听器。然而,防止“后退按钮”传播的技巧是 not that wrong,尽管我们希望有一个不存在的 document.removeAllEventListener('backbutton')
    【解决方案2】:

    我发现了如何撤消它(返回按钮以前的功能):

    您的观察者被推送到this.platform.backButton.observers 数组。所以你只需要弹出列表的最后一个元素:

    this.platform.backButton.observers.pop();
    

    希望它对某人有所帮助。

    【讨论】:

      【解决方案3】:

      05-02-2020

      这对我有用。

      app.component.ts

        

      async initializeApp(): Promise<void> {
          await this.platform.ready();
         
          this.platform.backButton.subscribeWithPriority(1, () => { // to disable hardware back button on whole app
          });
      
        }
      

      【讨论】:

      • 这是一个简单快捷的解决方法,比js
      【解决方案4】:

      我找到了更好的方法来避免返回按钮设备,并在你想要的任何页面上禁用返回

      import { Router, NavigationEnd } from '@angular/router';
      
      @Injectable({
        providedIn: 'root'
      })
      export class DisableBackService {
        // page disable back button
        private blackLists: string[] = ['/tab/wall', '/event-list', '/tutorial', '/offline-message'];
      
        constructor(private router: Router) {
          // call every have change page
          this.router.events.subscribe((ev) => {
            if (ev instanceof NavigationEnd) {
              const blackList = this.blackLists.find(el => ev.url.includes(el));
              if (blackList) {
                this.disableBack();
              } else {
                this.enableBack();
              }
            }
          });
        }
      
        private logger() {
          console.log('disable back button');
        }
      
        disableBack() {
          document.addEventListener('backbutton', this.logger, false);
        }
      
        enableBack() {
          document.removeEventListener('backbutton', this.logger, false);
        }
      }
      

      【讨论】:

      • 在哪里添加这个服务?直接在app模块中
      【解决方案5】:

      提到使用capacitor 处理后退按钮可能相关,这将禁用文档中描述的默认后退按钮行为:

          /**
           * Listen for the hardware back button event (Android only). Listening for this event will disable the
           * default back button behaviour, so you might want to call `window.history.back()` manually.
           * If you want to close the app, call `App.exitApp()`.
           */
          addListener(eventName: 'backButton', listenerFunc: (data: AppUrlOpen) => void): PluginListenerHandle;
      

      用法:

      import { Plugins, AppState } from '@capacitor/core';
      
      const { App } = Plugins;
      
      App.addListener('backButton', (data: AppUrlOpen) => {
        console.log('User pushed the back button, default behaviour has been overiden');
      });
      
      

      【讨论】:

        【解决方案6】:

        您可以实现禁用特定页面的硬件返回按钮。在 ionic 4 中使用以下代码。

         ionViewDidEnter() {
            this.backbutton = this.platform.backButton.observers.pop();
          }
        
          ionViewWillLeave() {
            this.platform.backButton.observers.push(this.backbutton);
          }
        

        【讨论】:

          【解决方案7】:

          在ionic 5中使用LoadingController时禁用硬件后退按钮。参考前两个答案并将它们合并到加载控制器代码中

          import {
                  LoadingController,
                  Platform
              } from '@ionic/angular';
              constructor(public platform: Platform, private loadingController: LoadingController) {}
          
          async presentLoading() {
              this.platform.backButton.subscribeWithPriority(10, () => {
                  document.addEventListener('backbutton', () => {}, false);
              });
              const loading = await this.loadingController.create({
                  spinner: 'circles',
                  keyboardClose: true,
                  message: 'Please Wait'
              }).then((res) => {
          
                  res.onDidDismiss().then((d) => {
                      this.platform.backButton.observers.pop();
                  })
                  return res.present()
              })
              return loading;
          }
          

          【讨论】:

            猜你喜欢
            • 2019-05-01
            • 2021-11-21
            • 2020-01-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-01-13
            • 1970-01-01
            • 2014-12-20
            相关资源
            最近更新 更多