端能力是 App 开发中非常重要的基础技术,在 js-native 这种框架研发过程中要保证多端统一,也就是说在 H5 页面中当调用一个端能力的时候,需要提供统一的调用 API,如下:
// bad
function getSystemInfo() {
if (isIos) {
// send msg to iOS
}
else if (isAndroid) {
// send msg to android
}
}
// good
function getSystemInfo() {
// send msg to all platform
}
要想保证 API 的一致性,必须对 JS 与 Native 通信的方式有一个彻底的了解。我主要了解到以下几种通信方式:
postMessage(iOS WKWebview)
这种方式是在 iOS 中处理消息非常方便,但是在 Android 中并不支持。
- (void)userContentController:(WKUserContentController *)uc
didReceiveScriptMessage:(WKScriptMessage *)message
{
// 接收到消息,并处理
}
// 消息发送
window.webkit.messageHandlers.SYJSBridge.postMessage(msg);
promp