简体   繁体   中英

How to detect if the back button is pressed in mobile phone

Please how can I detect if the back button is been pressed in a mobile phone as shown in the image below 在此处输入图片说明

I tried using the normal way its been done on desktop like this

$(document).keypress(function(e){
    if(e.keyCode == 8){
        alert();
    }
});

But it's not working on mobile phones. Please anyone with a better clue?

One option is to use jquery mobile.

Here is a code sample (of jquery mobile)

$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    // do something
  }
  if (direction == 'forward') {
    // do something else
  }
});

Another option would be to add a 'hardwareBackPress' event listener, as demonstrated in this react-native code sample

According to this source , to detect the 'back' key, KEYCODE_BACK = 4 on Android.

Alternatively, you could integrate mobile-detect.js

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM