Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebView 與 JS 互動:從靜態到動態注入

編輯:關於 Android 程式設計

WebView 與 JavaScript 的互動大致可涵蓋以下幾種組合:

1、本地 html 與本地 html 裡的 js 互動
2、本地 html 與本地 js 互動
3、網絡 html 與網絡 js 互動
4、網絡 html 與本地 js 互動
5、各情況下的動態添加 js

以上五點都能用同一套方式模擬。本篇以「本地 html 與本地 js 互動」(含動態添加 js)為例。

6、攔截 url 請求(在 webview 加載完成後觸發的請求 url)
7、攔截 url 請求後返回自己封裝的數據(基於第 6 點,加載完成後觸發一些請求數據的 url 時攔截並自行封裝數據返回給 webview)

註:第 6、7 點將在下一篇博客中介紹。

webview 能做什麼?以下引用自原作者 vanezkw:

1)webView 可以用 html 做介面排版,雖然目前用的人還不多,但當客戶端需要複雜的動態圖文混排時,它是個不錯的選擇。
2)直接顯示網頁,這也是它最基本的功能。
3)和 js 互動——如果你的 js 功底比 java 好,那用這種方式處理一些複雜邏輯會是個不錯的選擇。

一、本地 html 與本地 js 互動(本地 html 引用本地 js)

註:此例為本地 html 引用本地 js。若想把 js 直接寫進 html,只需把 js.js 的程式碼複製到 html 對應的 <script></script> 標籤內即可。

首先在 assets 資料夾裡要有兩個檔案:.html 與 .js。

test.html:

 <a href="https://www.baidu.com">js中調用本地方法</a> <script src="file:///android_asset/js.js"></script>

js.js:

 function funFromjs(){ document.getElementById("mydiv").innerHTML="獲取id為mydiv的元素,並向其中添加文字!"; myObj.fun1FromAndroid("我的myObj回調"); }

activity.xml:

 <relativelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.yanqy.yqy_jsexample.MainActivity" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"><button android:id="@+id/mButton" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="UI觸發webview中的js"> <webview android:id="@+id/mWebView" android:layout_below="@+id/mButton" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_width="wrap_content"> </webview></button></relativelayout>

MainActivity.java:

 package com.yanqy.yqy_jsexample; import android.content.Context; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private WebView mWebView; private Button mBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtn = (Button) findViewById(R.id.mButton); mWebView = (WebView) findViewById(R.id.mWebView); //設置編碼 mWebView.getSettings().setDefaultTextEncodingName("utf-8"); //支持js mWebView.getSettings().setJavaScriptEnabled(true); //設置背景顏色 透明 mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0)); //設置本地調用對象及其接口 mWebView.addJavascriptInterface(new JavaScriptObject(this), "myObj"); //載入網頁 mWebView.loadUrl("file:///android_asset/test.html"); //點擊調用js中方法 mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWebView.loadUrl("javascript:funFromjs()"); } }); } final class JavaScriptObject { private Context mContxt; public JavaScriptObject(Context mContxt) { this.mContxt = mContxt; } @JavascriptInterface //sdk17版本以上加上注解 public void funFromAndroid(String name) { //在此可以通過js返回數據name進行操作 Toast.makeText(mContxt, "調用funFromAndroid:" + name, Toast.LENGTH_LONG).show(); } } } 

這裡的關鍵有三步:先在 Settings 裡開啟 setJavaScriptEnabled(true);再用 addJavascriptInterface 把一個本地物件以 myObj 之名注入到 WebView,讓 js 能反向呼叫 Java;最後 Java 端透過 loadUrl("javascript:...") 主動呼叫 js 函數。

二、本地 html 動態添加 js

同上,首先在 assets 資料夾裡要有 .html 與 .js 檔案。

test.html——這次把 <script></script> 標籤及其內容刪除:

 

js中調用本地方法

js.js(與第一點相同,不變):

 function funFromjs(){ myObj.fun1FromAndroid("第一個js回調"); }

MainActivity.java——需要讀取 js 並動態添加到 webview 中,才能達到「動態添加 js」的效果。先把 js 讀進一個 String:

 //js文本 private String wholeJS = ""
 //獲取js文本 InputStream mIs = null; try { mIs = getResources().getAssets().open("js.js"); if(mIs != null){ byte buff[] = new byte[1024]; ByteArrayOutputStream fromFile = new ByteArrayOutputStream(); FileOutputStream out = null; do { int numread = 0; numread = mIs.read(buff); if (numread <= 0) { break; } fromFile.write(buff, 0, numread); } while (true); wholeJS = fromFile.toString(); }else{ Toast.makeText(MainActivity.this, "js加載失敗", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); }

然後把讀到的 js 注入 webview:

 mWebView.loadUrl("javascript:" + wholeJS);

MainActivity 完整程式碼:

 package com.yanqy.yqy_jsexample; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private WebView mWebView; private Button mBtn; //js文本 private String wholeJS = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtn = (Button) findViewById(R.id.mButton); mWebView = (WebView) findViewById(R.id.mWebView); //設置編碼 mWebView.getSettings().setDefaultTextEncodingName("utf-8"); //支持js mWebView.getSettings().setJavaScriptEnabled(true); //設置背景顏色 透明 mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0)); //設置本地調用對象及其接口 mWebView.addJavascriptInterface(new JavaScriptObject(this), "myObj"); //載入網頁 mWebView.loadUrl("file:///android_asset/test.html"); //點擊調用js中方法 mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //觸發html中的js mWebView.loadUrl("javascript:funFromjs()"); } }); //獲取js文本 InputStream mIs = null; try { mIs = getResources().getAssets().open("js.js"); if(mIs != null){ byte buff[] = new byte[1024]; ByteArrayOutputStream fromFile = new ByteArrayOutputStream(); FileOutputStream out = null; do { int numread = 0; numread = mIs.read(buff); if (numread <= 0) { break; } fromFile.write(buff, 0, numread); } while (true); wholeJS = fromFile.toString(); }else{ Toast.makeText(MainActivity.this, "js加載失敗", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } //webview添加讀取的js mWebView.loadUrl("javascript:" + wholeJS); } final class JavaScriptObject { private Context mContxt; public JavaScriptObject(Context mContxt) { this.mContxt = mContxt; } @JavascriptInterface //sdk17版本以上加上注解 public void funFromAndroid(String name) { //在此可以通過js返回數據name進行操作 Toast.makeText(mContxt, "調用funFromAndroid:" + name, Toast.LENGTH_LONG).show(); } } } 

activity_main.xml 與第一點相同,不變。

第 6、7 點將在下一篇博客中介紹,內容關於攔截請求,以及 webview 一些常用的監聽事件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved