# FrontEnd 與 Native 的串接 ## Native 啟動 Webview 的時候,需要加上 User Agent 的後綴 ``` "/XXX_APP" --> XXX APP ``` iOS User-Agent 加後綴 ``` fileprivate func setNavigatorUserAgent() { // 由native的webview在user agent加上特定字串,方便web辨別是否為mRich app self.tempWebView.evaluateJavaScript("navigator.userAgent") { [weak self] (result, error) in if let userAgent = result as? String { self?.webView.customUserAgent = userAgent + "/ON_MRICH_APP" } } } ``` android User-Agent 加後綴 ``` class WebViewSettings { companion object SETTING { fun initWebView(context : Activity? , webview : WebView?) { // 加mobile物件 webview?.addJavascriptInterface(WebAppInterface(context), "mobile") // User-Agent 加後綴 val webSettings = webview?.getSettings() val userAgentStr = webSettings?.getUserAgentString() webSettings?.setUserAgentString(userAgentStr + "/ON_MRICH_APP") ... } } } ``` ## FrontEnd Call Native ### Request Sample ``` { tag:'XXXXX', uuid: '20d8e5fe-d9bc-11e9-8a34-2a2ae2dbcce4', requestData:{...} or {} } ``` 以上JSON物件會轉成JSONSTRING => message,使用postMessage呼叫Native #### postMessage() ##### iOS Request * 寫在Web端的呼叫iOS的語法 ``` window.webkit.messageHandlers.mobile.postMessage(message); ``` * iOS使用以下方式串接 ``` extension ViewController: WKScriptMessageHandler { func userContentController( _userContentController: WKUserContentController, didReceive message: WKScriptMessage ){ let name = message.name if name == "mobile" { ... } } } ``` ##### android Request * 寫在Web端的呼叫android語法 ``` window.mobile.postMessage(message); ``` * android使用以下方式串接 ``` @JavascriptInterface fun postMessage(param : String) : String? { … } ``` ## Native Callbakc to FrontEnd ### Response Sample ``` { tag: 'XXXX' uuid: '0d8e5fe-d9bc-11e9-8a34-2a2ae2dbcce4'(與request帶的uuid相同) returnCode: '...' returnMsg: 'xxx' returnData: {...} or {} } ``` 以上JSON物件要轉成JSONSTRING => message Native要執行FrontEnd的JS callback Method ``` window.executeAsync(message) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up