ผมทำโปรเจกต์ที่งาน ต้องเชื่อมหลาย Components ผ่าน Messages แต่ละตัวมี Logic และ Code Language ต่างกัน ทำให้อยากเข้าใจทุกวิธีที่ Platforms ต่างๆ ใช้ Communication
บทความนี้อธิบาย Cross-Origin Communication Bridges พร้อมตัวอย่าง Simple แต่ Informative
จะมี Bridge Puns เยอะ 😄
คุณได้รับคำเตือนแล้ว
ถ้าอยากเขียนโค้ดทันที มี Links GitHub Repositories ท้ายบทความ
ปกติ JavaScript รันใน Browser บน iOS เป็น UIWebView หรือ WKWebView บน Android เป็น WebView
iOS ซับซ้อนกว่า จะอธิบาย Bridge ที่นี่ก่อน
London Bridge is Falling Down (iOS)
iOS 8 ขึ้นไป Apple แนะนำ WKWebView แทน UIWebView บทความนี้ครอบคลุมแค่ WKWebView
สำหรับ UIWebView Reference ดู ที่นี่
ส่ง Messages จาก WKWebView ไป JavaScript ใช้ Method:
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *error))completionHandler;
รับ Messages จาก JavaScript ใน WKWebView ต้อง:
- สร้าง Instance ของ
WKWebViewConfiguration - สร้าง Instance ของ
WKUserContentController - Add Script Message Handler ไป Configuration (ส่วนนี้ Bridge Gap) Action นี้ Register Message Handler บน Window Object Path: window.webkit.messageHandlers.MSG_HANDLER_NAME
- ทำให้ Class Implement Message Handler Protocol เพิ่ม
<WKScriptMessageHandler>บนสุดไฟล์ - Implement
userContentController:didReceiveScriptMessage(Handle Receive Messages จาก JavaScript)
Building Bridges
สมมติมี HTML Page:
<html>
<head>
<title>Javascript-iOS Communication</title>
</head>
<body>
<script>
window.webkit.messageHandlers.myOwnJSHandler.postMessage("Hello World!");
</script>
</body>
</html>
Native Code Implement ขั้นตอนข้างต้น:
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
// 4
@interface ViewController : UIViewController <WKScriptMessageHandler>
@property(nonatomic, strong) WKWebView *webview;
Violà! มี Full JavaScript - iOS Communication แล้ว!
Crossing The Bridge (Android)
Android ง่ายและ Friendly มาก Steps เพียงเล็กน้อย:
- สร้าง Instance ของ
WebViewObject - Enable JavaScript ใน WebView (setJavaScriptEnabled)
- Set Custom JavaScript Interface (Hold Methods ที่ Visible ไป JavaScript)
- Method ที่ต้องการ Expose ให้ JavaScript ต้องมี Annotation @JavascriptInterface ก่อน Declaration
สมมติ HTML File และ Android App เรียบร้อยแล้ว
ไปแล้ว! คุณเป็น Native Communication Ninja แล้ว! 🥷
Repository Links:
AndroidtoJS RepositoryiOStoJS Repository⚠️ Important Note Regarding iOS ⚠️
ตอน Destroy WKWebView จำเป็น ต้อง Remove Script Message Handler หากไม่ทำ Script Message Handler จะ Hold Reference ไป WKWebView Memory Leaks จะเกิดเมื่อสร้าง WKWebViews ใหม่