Android WebView使用笔记(二) JS注入

使用场景:

  在一个第三方的web页面,如果想在页面后面拼加内容(如资讯文章需要拼加广告),如果使用WebView后面加上Android 的Native View的方式,可能会有页面卡顿或者其他问题,比如滑动问题等。

  这时,其实还可以使用注入JS的方式,直接在页面的body后面加入H5形式的内容页面

效果如图:

   WebView中加载百度首页,点击“加载JS”后注入我们写好的JS,会在页面底部添加一行文字“这个是添加的内容”;

   点击调用JS会调用我们注入的JS方法,然后Alert一个信息。

     


   注入的JS:

      

javascript:{
 $("body").append("<div style='position:fixed; bottom:15px'><b>这个是添加的内容</b></div>");

 function myJsFunction(data) {
  alert("myJsFunction:" + data);
  }

}

  可以看到代码很简单,只是在页面的body后追加了一段h5代码,

  声明了一个JS函数:myJsFunction


  布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="15dp"
    tools:context="com.muzi.js.MainActivity">

    <Button
        android:id="@+id/btn_load_js"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载js" />

    <Button
        android:id="@+id/btn_call_js"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="调用js" />

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


package com.muzi.js;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String URL = "https://www.baidu.com";

    private Button mBtnLoadJs;
    private Button mBtnCallJs;
    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.web_view);
        mBtnLoadJs = (Button) findViewById(R.id.btn_load_js);
        mBtnCallJs = (Button) findViewById(R.id.btn_call_js);

        mBtnLoadJs.setOnClickListener(this);
        mBtnCallJs.setOnClickListener(this);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });

        mWebView.loadUrl(URL);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_call_js:
                mWebView.evaluateJavascript(String.format(Locale.getDefault(), "javascript:myJsFunction(%s)", "\"hello\""), null);
                break;
            case R.id.btn_load_js:
                String js = readAssertFile(getApplicationContext(), "myJs"); //io操作需要放到子线程,这里是非正当操作
                mWebView.evaluateJavascript(js, null);
                break;
        }
    }

    public static String readAssertFile(Context context, String file) {
        String s = null;
        InputStream inputStream = null;
        try {
            inputStream = context.getAssets().open(file);
            s = readTextFromStream(inputStream);
        } catch (IOException e) {
            Log.w("tag", e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return s;
    }

    public static String readTextFromStream(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
        }
        return outputStream.toString();
    }
}


猜你喜欢

转载自blog.csdn.net/qqwuy_muzi/article/details/79975741
今日推荐