uni-app disable back button/back key

foreword

When using uni-app to develop native applications, the following requirements are encountered:

  1. Need to disable physical back button, gesture back.
  2. uni.navigateBack still works.

accomplish

  1. Disable physical return in onBackPress() of the current page
  2. In pages.json, remove the return button of the current page
  3. In the mounted() of the current page, hide the return button of the current page (for invalid settings in pages.json)

Specific demo code

1. In the current page, onBackPress() controls whether to disable the back button and gesture return.

onBackPress(options) {
  // 触发返回就会调用此方法,这里实现的是禁用物理返回,顶部导航栏的自定义返回 uni.navigateBack 仍可使用
  if (options.from == 'backbutton') {
    return true;
  } else if (options.from == 'navigateBack') {
    return false;
  }
},

options.from in onBackPress() has two values: backbutton and navigateBack.

  • backbutton: Indicates that the source is the native back button in the upper left corner, the Android back key or the Android gesture back.
  • navigateBack: Indicates that the source is the custom back button on the top navigation bar. Using the return api in uni-app : uni.navigateBack(OBJECT),

2. In pages.json, remove the return button of the current page, mainly setting: titleNView

{
  "path": "pages/update/update",
  "style": {
    "navigationStyle": "custom", // 取消本页面的导航栏
    "app-plus": {
      "animationType": "fade-in", // 设置fade-in淡入动画,为最合理的动画类型
      "background": "transparent", // 背景透明
      "backgroundColor": "rgba(0,0,0,0)", // 背景透明
      "popGesture": "none" ,// 关闭IOS屏幕左边滑动关闭当前页面的功能
      "titleNView": { //  隐藏当前页面的返回按钮
        "titleSize": "18px",
        "autoBackButton": false // 禁用原生导航栏
      }
    }
  }
}

3. In the current page, in mounted(), hide the back button of the current page (not necessary)

mounted(){
  //pages.json中设置autoBackButton:false 无效的,可以在需要去除导航返回的页面中的mounted钩子里加上如下代码段
  var backbutton = document.getElementsByClassName('uni-page-head-hd')[0]
  if(backbutton) backbutton.style.display = 'none';
},

The above is the relevant implementation logic for disabling the physical return button and gesture return.

Guess you like

Origin blog.csdn.net/loveliqi/article/details/125741106