先解釋一個名詞吧 Hybrid, 相信能看到這篇文章的同學對這個詞都不會感到陌生, 可能愛恨交叉的感覺會更強烈一些...
回到正題, Hybrid翻譯過來叫混合,混合物,在前端世界里有一個詞語叫混合開發便是它,大白話點就是將網頁內嵌在原生app中,然后產生一系列的交互
常用的交互方式
-
雙方約定協議(schema)
-
雙方約定函數
雙方約定協議(schema)
這里以android 為例,android 中可以通過WebViewClient 的回調方法shouldOverrideUrlLoading ()攔截 url, 然后解析該 url 的協議, 如果檢測到是預先約定好的協議,就調用相應方法
協議式的通信適用於單向交互, 客戶端想要回傳給我們參數比較復雜
代碼理解
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button type="button" id="button1" onclick="callAndroid()">點擊調用Android代碼</button> <script> function callAndroid() { /*約定的url協議為:js://webview?arg1=111&arg2=222*/ location.href = "js://webview?arg1=111&arg2=222"; } </script> </body> </html>
雙方約定函數
簡單來說,就是客戶端為我們做了一層關系映射, 也可以理解原生app端會向webview暴露一個頂層對象,就像js中的window,這個對象包含web需要但不具備因此由原生實現的一些方法
代碼理解
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <!-- 點擊按鈕則調用jsbridge函數 --> <button type="button" id="button1" onclick="jsbridge()">Hello</button>
<script> function jsbridge() { // 由於對象映射,所以調用test對象等於調用Android映射的對象 test.hello("js調用了原生app暴漏出來jsbridge中的hello方法"); } </script> </body> </html>
總結
-
約定協議(native攔截http協議進行判讀是否是定義好的協議)
-
約定函數(native向webview注入頂級對象)