1.获取h5 plus对象
监听plusready事件
document.addEventListener('plusready', function () {
}
这个可以在index.html页面中直接写,但是对于一个vue开发的app来说,写在index.html的内容都会显得low
所以采用另外的方法,现在全局注册plusready事件,可以在任意vue组件中调用,
定义plusready.js
const plusExtends = fn => {
if (window.plus) {
setTimeout(fn, 0)
} else {
document.addEventListener('plusready', fn, false)
}
}
export default plusExtends
main.js内引入注册
import plusReady from './assets/js/plusready.js'
Vue.prototype.plusReady = plusReady;
接下来就可以直接使用,例如调用手机联系人:
this.plusReady(()=>{
plus.contacts.getAddressBook( plus.contacts.ADDRESSBOOK_PHONE,
function( addressbook ) {
addressbook.find(["displayName","phoneNumbers"],
function(contacts){
var contactsList = JSON.stringify(contacts);
console.log(contactsList)
}, function () {
console.log("获取通讯录失败")
}, {
multiple:true
});
},
function ( error ) {
alert("Get address book failed: " + error.message);
console.log("获取通讯录失败")
});
});
如果联机调试在控制台你会看到通讯录的整体json输出
当然上面只是举例,目的是退出应用,下面看代码就好
created(){
/***
* 设置app是否可回退,以及退出系统,在安卓有效,ios没有一次性退出系统的操作
* */
let _this = this;
this.plusReady(()=>{
var webview = plus.webview.currentWebview();
webview.setBounce({position:{top:'100px'},changeoffset:{top:'0px'}});//设置Webview窗口的回弹效果
var first = null;
plus.key.addEventListener('backbutton', function () {
webview.canBack(function (e) {
if (e.canBack) {// 获取Webview窗口是否可后退 ,可后退时
let path = _this.$route.path;
if(path === "/index"){// 如果回退到了首页,则关闭禁止回退
/***
* 1秒内,连续两次按返回键,则退出应用;
* */
if (!first) {// first没有值时
first = new Date().getTime();
_this.$toast({message:"再按一次退出应用",duration:1000});
setTimeout(function () {
first = null
}, 1000)
} else {
if (new Date().getTime() - first < 1500) {
localStorage.clear();
sessionStorage.clear();
plus.runtime.quit();
}
}
}
else {// 否则可以继续回退
webview.back();
}
} else {
if (!first) {// first没有值时
first = new Date().getTime();
_this.$toast({message:"再按一次退出应用",duration:1000});
setTimeout(function () {
first = null
}, 1000)
} else {
if (new Date().getTime() - first < 1500) {
localStorage.clear();
sessionStorage.clear();
plus.runtime.quit();
}
}
}
})
})
})
},
完事,接下来解决网络状态的问题