混合開發中JS與APP通訊的實現原理:javascript
JS經過schema協議,傳遞參數和全局回調函數給APP端html
APP執行完(如微信掃一掃)後,調用協議中傳入的回調函數,在前端執行回調處理。前端
默認寫法:java
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hybrid中schema協議的使用</title>
</head>
<body>
<button id="btn1">掃一掃</button>
<script>
function invokeScan(){微信
//APP執行的回調函數
window['_invoke_scan_callback'] = function(result){
alert(result);
}app
var iframe = document.createElement("iframe");
iframe.style.display="none";
//iframe.src = 'weixin://dl/scan'; //重要
iframe.src = 'weixin://dl/scan?k1=v1&k2=v2&k3=v3callback=_invoke_scan_callback';
var body = document.body;
body.appendChild(iframe);
setTimeout(function(){
body.removeChild(iframe);
iframe = null;
});
}
document.getElementById("btn1").addEventListener("click",function(){
invokeScan();
});
</script>
</body>
</html>函數
封裝後以下:spa
APP中的schema.jscode
//封裝schemahtm
//若是data和callback非必填參數,可在函數內作些兼容性處理
function invokeScan(type,data,callback){
var iframe = document.createElement("iframe");
iframe.style.display="none";
//iframe.src = 'weixin://dl/scan'; //重要
//
//拼接schema協議:
var schema = 'myapp://dl';
schema += "/"+type; //傳入類型
schema += "?a=a"; //避免判斷是否加?
if(typeof data != "undefined"){
for(var key in data){
if(data.hasOwnProperty(key)){
_src+="&"+key+"="+data[key];
}
}
}
//協議中增長callback回調函數
var callBackName = '';
//APP執行的回調函數
if(typeof callback != "undefine"){
if(typeof callback ==="string"){ //傳入的是回調名稱
callBackName = callback;
}
else{ //傳入的是回調函數
callBackName = type + Date.now(); // Date.now() == new Date().getTIme()
}
window[callBackName] = callback;
_src+='&callback='callBackName;
}
iframe.src = _src;
var body = document.body;
body.appendChild(iframe);
setTimeout(function(){
body.removeChild(iframe);
iframe = null;
});
}
//將schena協議暴露給全局
/*
寫法一:
window.invokes = {
scan:function(data,callback){ //掃一掃
invokeScan("scan");
},
share:function(data,callback){ //拍照
invokeScan("share",data,callback)
}
}
*/
//寫法二:功能進一步才分
window.invoke = {
scan:_scan,
share:_share
}
function _scan(data,callback){ //掃一掃
invokeScan("scan");
}
function _share(data,callback){ //拍照
invokeScan("share",data,callback)
}
window.init = function(id){
return document.getElementById(id);
}
APP中的html調用:
<body>
<button id="btn1">掃一掃</button>
<button id="btn2">拍照</button>
<script type="text/javascript" src="./schema.js"></script>
<script>
//封裝完成後,頁面調用方法以下
//
//掃一掃
init("btn1").addEventListener("click",function(){
window.invoke.scan();
});
//照相
init("btn2").addEventListener("click",function(){
window.invoke.share({"name":"zs","age":11},function(result){
if(result.code===0){
alert(result);
}
else{
alert(result.message);
}
});
});
</script>
</body>