Ionic 4如何禁用设备硬件返回按钮?

6

我正在使用angular路由(@angular/router)来为ionic 4项目禁用设备的后退按钮,在ionic 4中prevent-default不起作用,以下是我的代码

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

我无法禁用设备的返回按钮,请帮忙解决。

7个回答

14
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中并在平台中导入 :) - Davide Martina
加载时是否可以添加并在加载结束时启用? - Rakesh Roy
如何移除它? - manish kumar
我该如何调整这段代码,使得返回按钮能够导航回登录界面?我尝试在你的“hello”行后添加this.router.navigate(['/login']),但是出现了错误:无法读取未定义的属性“navigate”。我已经在构造函数中添加了private router: Router,但仍然出现相同的错误。 - lepton
你的代码虽然可以工作,但技术上是错误的,因为每次有人按后退按钮时都会添加一个事件侦听器。然而,防止“backbutton”传播的技巧并不是那么错(https://dev59.com/e2Ik5IYBdhLWcg3wN71j#46986927),尽管我们希望有一个不存在的`document.removeAllEventListener('backbutton')`。 - Flavien Volken
这样做会导致每次按下后退按钮时都订阅backbutton事件。 - Mahmood Dehghan

7
我发现如何撤销它(恢复返回按钮的先前功能):
您的观察者被推到this.platform.backButton.observers数组中,因此您只需弹出列表的最后一个元素即可:
this.platform.backButton.observers.pop();

希望能对某些人有所帮助。

1
这里提供最干净的解决方案。 - inorganik

5

2020年5月2日

这对我有效。

app.component.ts

  

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

  }

这是一个简单而快速的修复。谢谢。 - Manoj Alwis

1
您可以针对特定页面禁用硬件返回按钮。在ionic 4中使用以下代码即可实现。
 ionViewDidEnter() {
    this.backbutton = this.platform.backButton.observers.pop();
  }

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

0

我找到了更好的方法来避免设备上的返回按钮,并使其在任何页面上禁用返回功能。

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

在哪里添加这个服务?直接在应用程序模块中添加。 - hardiksa

0

提到使用电容器处理返回按钮可能是相关的,这将禁用默认的返回按钮行为,如文档所述:

    /**
     * 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');
});


0

在使用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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接