亲宝软件园·资讯

展开

vue项目中监听手机物理返回键的实现

竿牍 人气:0

背景:项目中有一个场景要监听android手机物理返回键,但是app和js的中间件又没提供这个事件的监听,只能百度纯js实现了

第一步:

xback.js

;!function(pkg, undefined){
 var STATE = 'x-back';
 var element;
 var onPopState = function(event){
  event.state === STATE && fire();
 }
 var record = function(state){
  history.pushState(state, null, location.href);
 }
 var fire = function(){
  var event = document.createEvent('Events');
  event.initEvent(STATE, false, false);
  element.dispatchEvent(event);
 }
 var listen = function(listener){
   element.addEventListener(STATE, listener, false);
  }
 ;!function(){
  element = document.createElement('span');
  window.addEventListener('popstate', onPopState);
  this.listen = listen;
  this.record = record(STATE);
  record(STATE);
 }.call(window[pkg] = window[pkg] || {});
}('XBack');

第二步:

加载xback.js文件

<remote-script src="../js/xback.js" @load="loadXBack"></remote-script>

自定义组件remote-script可以参考我另外的一篇文章:https:

第三步:

监听返回键事件

methods: {
  // JavaScript监听手机物理返回键
   loadXBack () {
    window.XBack.listen(() => {
     this.dialog = this.$createDialog({
      type: 'confirm',
      content: `确定返回吗?`,
      confirmButton: {
       text: '确定',
       active: true,
       disabled: false
      },
      cancelButton: {
       text: '取消',
       active: false,
       disabled: false
      },
      onConfirm: () => {
       this.dialog.hide()
       this.close()
      },
      onCancel: () => {
       this.dialog.hide()
       window.history.pushState('x-back', null, window.location.href)
      }
     })
     this.dialog.show()
    })
   },
}

加载全部内容

相关教程
猜你喜欢
用户评论