混合开发中JS与APP通信的实现原理:
JS通过schema协议,传递参数和全局回调函数给APP端
APP执行完(如微信扫一扫)后,调用协议中传入的回调函数,在前端执行回调处理。
默认写法:
<!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);
}
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>
封装后如下:
APP中的schema.js
//封装schema
//如果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();
}
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>
原文地址:https://www.cnblogs.com/liuxu-xrl/p/8990520.html