1. 程式人生 > >H5中 JS 禁用安卓手機物理返回鍵 , 微信瀏覽器中也支援

H5中 JS 禁用安卓手機物理返回鍵 , 微信瀏覽器中也支援

直接引入以下程式碼就可以實現

	XBack = {};

	(function(XBack) {
		XBack.STATE = 'x - back';
		XBack.element;

		XBack.onPopState = function(event) {
			event.state === XBack.STATE && XBack.fire();
			XBack.record(XBack.STATE); //初始化事件時,push一下
		};

		XBack.record = function(state) {
			history.pushState(state, null, location.href);
		};

		XBack.fire = function() {
			var event = document.createEvent('Events');
			event.initEvent(XBack.STATE, false, false);
			XBack.element.dispatchEvent(event);
		};

		XBack.listen = function(listener) {
			XBack.element.addEventListener(XBack.STATE, listener, false);
		};

		XBack.init = function() {
			XBack.element = document.createElement('span');
			window.addEventListener('popstate', XBack.onPopState);
			XBack.record(XBack.STATE);
		};

	})(XBack); // 引入這段js檔案

	XBack.init();
	XBack.listen(function() {});