ionic 4防止/禁用设备硬件后退按钮

时间:2019-03-21 06:38:26

标签: angular ionic3 ionic4 angular-router

我在ionic 4项目中使用了角向布线(@ angular / router)来禁用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);
        }
      });
    });

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

8 个答案:

答案 0 :(得分:3)

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

  }

答案 1 :(得分:2)

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

答案 2 :(得分:1)

我发现了如何撤消它(赋予后退按钮以前的功能):

您的观察者被推送到this.platform.backButton.observers数组。因此,您只需要弹出列表的最后一个元素即可:

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

希望对您有所帮助。

答案 3 :(得分:0)

这是管理设备后退按钮的另一个最佳选择:

 manageBack()
{
   this.platform.registerBackButtonAction(() => {
        let activeVC = this.navCtrl.getActive();


      console.log(activeVC.name)

        let page = activeVC.instance;

        console.log(page)

        if (page instanceof PageName) {
          try {
              //this.platform.exitApp(); 
            // this.navCtrl.popAll();
          } catch (e) {
              console.log("back action listener error :" + e);
          }
        }
        //  the default handler
      });
}

答案 4 :(得分:0)

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

Azure Functions Core Tools (3.0.2245 Commit hash: 1d094e2f3ef79b9a478a1621ea7ec3f93ac1910d)
Function Runtime Version: 3.0.13139.0
[3/16/2020 6:02:11 PM] Building host: startup suppressed: 'False', configuration suppressed: 'False', startup operation id: 'a37bba12-9125-4af6-8c10-26daef57ef90'
[3/16/2020 6:02:11 PM] Reading host configuration file 'C:\Users\Peter\Desktop\UploadVideo\YoutubeUploadFunction\YoutubeUploadFunction\bin\Debug\netcoreapp3.0\host.json'
[3/16/2020 6:02:11 PM] Host configuration file read:
[3/16/2020 6:02:11 PM] {
[3/16/2020 6:02:11 PM]   "version": "2.0"
[3/16/2020 6:02:11 PM] }
[3/16/2020 6:02:11 PM] Reading functions metadata
[3/16/2020 6:02:11 PM] 1 functions found
[3/16/2020 6:02:11 PM] Loading startup extension 'AzureStorage'
[3/16/2020 6:02:11 PM] Loaded extension 'AzureStorage' (3.0.4.0)
[3/16/2020 6:02:11 PM] Initializing Warmup Extension.
[3/16/2020 6:02:11 PM] Initializing Host. OperationId: 'a37bba12-9125-4af6-8c10-26daef57ef90'.
[3/16/2020 6:02:11 PM] Host initialization: ConsecutiveErrors=0, StartupCount=1, OperationId=a37bba12-9125-4af6-8c10-26daef57ef90
[3/16/2020 6:02:11 PM] LoggerFilterOptions
[3/16/2020 6:02:11 PM] {
[3/16/2020 6:02:11 PM]   "MinLevel": "None",
[3/16/2020 6:02:11 PM]   "Rules": [
[3/16/2020 6:02:11 PM]     {
[3/16/2020 6:02:11 PM]       "ProviderName": null,
[3/16/2020 6:02:11 PM]       "CategoryName": null,
[3/16/2020 6:02:11 PM]       "LogLevel": null,
[3/16/2020 6:02:11 PM]       "Filter": "<AddFilter>b__0"
[3/16/2020 6:02:11 PM]     },
[3/16/2020 6:02:11 PM]     {
[3/16/2020 6:02:11 PM]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[3/16/2020 6:02:11 PM]       "CategoryName": null,
[3/16/2020 6:02:11 PM]       "LogLevel": "None",
[3/16/2020 6:02:11 PM]       "Filter": null
[3/16/2020 6:02:11 PM]     },
[3/16/2020 6:02:11 PM]     {
[3/16/2020 6:02:11 PM]       "ProviderName": "Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics.SystemLoggerProvider",
[3/16/2020 6:02:11 PM]       "CategoryName": null,
[3/16/2020 6:02:11 PM]       "LogLevel": null,
[3/16/2020 6:02:11 PM]       "Filter": "<AddFilter>b__0"
[3/16/2020 6:02:11 PM]     }
[3/16/2020 6:02:11 PM]   ]
[3/16/2020 6:02:11 PM] }
[3/16/2020 6:02:11 PM] FunctionResultAggregatorOptions
[3/16/2020 6:02:11 PM] {
[3/16/2020 6:02:11 PM]   "BatchSize": 1000,
[3/16/2020 6:02:11 PM]   "FlushTimeout": "00:00:30",
[3/16/2020 6:02:11 PM]   "IsEnabled": true
[3/16/2020 6:02:11 PM] }
[3/16/2020 6:02:11 PM] SingletonOptions
[3/16/2020 6:02:11 PM] {
[3/16/2020 6:02:11 PM]   "LockPeriod": "00:00:15",
[3/16/2020 6:02:11 PM]   "ListenerLockPeriod": "00:00:15",
[3/16/2020 6:02:11 PM]   "LockAcquisitionTimeout": "10675199.02:48:05.4775807",
[3/16/2020 6:02:12 PM]   "LockAcquisitionPollingInterval": "00:00:05",
[3/16/2020 6:02:12 PM]   "ListenerLockRecoveryPollingInterval": "00:01:00"
[3/16/2020 6:02:12 PM] }
[3/16/2020 6:02:12 PM] QueuesOptions
[3/16/2020 6:02:12 PM] {
[3/16/2020 6:02:12 PM]   "BatchSize": 16,
[3/16/2020 6:02:12 PM]   "NewBatchThreshold": 8,
[3/16/2020 6:02:12 PM]   "MaxPollingInterval": "00:00:02",
[3/16/2020 6:02:12 PM]   "MaxDequeueCount": 5,
[3/16/2020 6:02:12 PM]   "VisibilityTimeout": "00:00:00"
[3/16/2020 6:02:12 PM] }
[3/16/2020 6:02:12 PM] BlobsOptions
[3/16/2020 6:02:12 PM] {
[3/16/2020 6:02:12 PM]   "CentralizedPoisonQueue": false
[3/16/2020 6:02:12 PM] }
[3/16/2020 6:02:12 PM] HttpOptions
[3/16/2020 6:02:12 PM] {
[3/16/2020 6:02:12 PM]   "DynamicThrottlesEnabled": false,
[3/16/2020 6:02:12 PM]   "MaxConcurrentRequests": -1,
[3/16/2020 6:02:12 PM]   "MaxOutstandingRequests": -1,
[3/16/2020 6:02:12 PM]   "RoutePrefix": "api"
[3/16/2020 6:02:12 PM] }
[3/16/2020 6:02:12 PM] Starting JobHost
[3/16/2020 6:02:12 PM] Starting Host (HostId=desktopgq271u4-950774370, InstanceId=16bc66b5-e751-4c00-b383-6f705e303c13, Version=3.0.13139.0, ProcessId=5656, AppDomainId=1, InDebugMode=False, InDiagnosticMode=False, FunctionsExtensionVersion=(null))
[3/16/2020 6:02:12 PM] Loading functions metadata
[3/16/2020 6:02:12 PM] 1 functions loaded
[3/16/2020 6:02:12 PM] Generating 1 job function(s)
[3/16/2020 6:02:12 PM] Found the following functions:
[3/16/2020 6:02:12 PM] YoutubeUploadFunction.Function1.Run
[3/16/2020 6:02:12 PM]
[3/16/2020 6:02:14 PM] Initializing function HTTP routes
[3/16/2020 6:02:14 PM] No HTTP routes mapped
[3/16/2020 6:02:14 PM]
[3/16/2020 6:02:14 PM] Host initialized (2033ms)
[3/16/2020 6:02:14 PM] Host started (2485ms)
[3/16/2020 6:02:14 PM] Job host started
Hosting environment: Production
Content root path: C:\Users\Peter\Desktop\UploadVideo\YoutubeUploadFunction\YoutubeUploadFunction\bin\Debug\netcoreapp3.0
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.
[3/16/2020 6:02:19 PM] Host lock lease acquired by instance ID '000000000000000000000000A74A8599'.

C:\Users\Peter\AppData\Local\AzureFunctionsTools\Releases\3.4.1\cli_x64\func.exe (process 5656) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

答案 5 :(得分:0)

可能需要提及使用CSS only slideshow处理后退按钮,该操作会禁用文档中所述的默认后退按钮行为:

    /**
     * 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 :(得分:0)

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

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

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

答案 7 :(得分: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;
}