H5监听手机的返回键

方法一:

pushHistory(); 
window.addEventListener("popstate", function(e) { 
  alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能 
}, false); 
function pushHistory() {
  var state = { 
    title: "title", 
    url: "#"
  }; 
  window.history.pushState(state, "title", "#"); 
}

 

方法二:

var hiddenProperty = 'hidden' in document ? 'hidden' : 
  'webkitHidden' in document ? 'webkitHidden' : 
  'mozHidden' in document ? 'mozHidden' : 
  null;
var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
var onVisibilityChange = function(){
  if (!document[hiddenProperty]) { 
    console.log('页面非激活');
  }else{
    console.log('页面激活')
  }
}
document.addEventListener(visibilityChangeEvent, onVisibilityChange);

 

posted @ 2020-08-18 21:14  黑~白  阅读(3064)  评论(0编辑  收藏  举报