核心代码 pubSub.js
class PubSub {
constructor() {
this.handles = {}
}
on(type, handle) {
if (!this.handles[type]) {
this.handles[type] = []
}
this.handles[type].push(handle)
}
emit() {
var type = Array.prototype.shift.call(arguments)
if (!this.handles[type]) {
return false
}
for (var i = 0; i < this.handles[type].length; i++) {
var handle = this.handles[type][i]
handle.apply(this, arguments)
}
}
off(type, handle) {
let handles = this.handles[type]
if (!handle) {
handles.length = 0
} else {
for (var i = 0; i < handles.length; i++) {
var _handle = handles[i]
if (_handle === handle) {
handles.splice(i, 1)
}
}
}
}
}
export default new PubSub()
H5调用原生功能封装
export function jsBridge(data) {
return new Promise((resolve, reject) => {
let toNative
if (navigator.userAgent.includes('Android')) {
toNative = JSON.stringify(data)
console.log('<-----toNative--->', toNative)
try {
jsBridge && jsBridge.WebViewFunctionBridge(toNative)
} catch (error) {
reject("不在Android壳子里")
}
} else {
toNative = data
window.webkit.messageHandlers.XYFWebViewFunctionBridge.postMessage(
toNative
)
}
pubSub.on(data.type, (res) => {
resolve(res)
pubSub.off(data.type)
})
})
}
客户端注入H5方法回调
window.nativeCallBack = (data) => {
let resData = typeof data === 'object' ? data : JSON.parse(data)
pubSub.emit(resData.type, resData)
}
业务页面调用
jsBridge({
type: 'h5_get_device_id',
}).then((res) => {
console.log('获取到app 回调--->', res)
})