背景: 项目中有一个场景要监听 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');
- Windows.addEventListener('popstate', onPopState);
- this.listen = listen;
- this.record = record(STATE);
- record(STATE);
- }.call(Windows[pkg] = Windows[pkg] || {});
- }('XBack');
第二步:
加载 xback.JS 文件
<remote-script src="../js/xback.js" @load="loadXBack"></remote-script>
自定义组件 remote-script 可以参考我另外的一篇文章: https://www.jianshu.com/p/5a3445b968d1
第三步:
监听返回键事件
- methods: {
- // JavaScript 监听手机物理返回键
- loadXBack () {
- Windows.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()
- Windows.history.pushState('x-back', null, Windows.location.href)
- }
- })
- this.dialog.show()
- })
- },
- }
来源: http://www.jianshu.com/p/f1d1eaac6e8c