Android WebView and JS interaction (add JS dynamically)

Source: Internet
Author: User

1, local HTML and local HTML JS interaction

2, local HTML and local JS interaction

3. Network HTML and Network JS interaction

4. Network HTML and local JS interaction

5. Add JS dynamically in every situation

The above 5 points can be simulated in one way, in this article using the local HTML and local JS interaction (contains the action of adding JS dynamically)

6. Intercept URL request (after WebView loading completes , request URL triggered)

7, block the URL request after the return of their own encapsulated data (based on the 6th, after the load is completed, triggering some request data URL when blocking and self-encapsulated data returned to WebView)

Note: 6, 7 points will be introduced in the next blog


What can webview do? This paragraph references vanezkw thanks to the author

1), WebView can make use of HTML interface layout, although it is still relatively few people so use, but I believe that when some clients need complex graphics (graphics and text are dynamically generated) mixed in the time it is certainly a good choice.

2), directly display the Web page, this function is of course its most basic function.

3), and JS interaction. (If your JS base is better than Java, then it's a good idea to do some complicated processing in this way.)

first, local HTML and local JS interaction (local HTML reference local JS)Note: This example for local HTML and local JS interaction, such as to add JS in the local HTML, copy the Js.js code into the HTML corresponding <script></script> tags can

First of all, there are two files in the Assets folder. html,. js


Test.html

<body><a href= "http://www.baidu.com" >js call local method </a><script src= "File:///android_asset/js.js" ></script><p></p><div id= "Mydiv" ></div></body>
Js.js

function Funfromjs () {    document.getElementById ("mydiv"). Innerhtml= "Gets the element with the ID mydiv and adds text to it! ";    Myobj.fun1fromandroid ("My MYOBJ callback");}
Activity.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout 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"    tools:context= "com.yanqy.yqy_jsexample. Mainactivity ">    <button        android:layout_width=" wrap_content "        android:layout_height=" Wrap_ The content "        android:text=" UI triggers the JS "        android:id=" @+id/mbutton "        android:layout_alignparenttop=" in WebView True "        android:layout_centerhorizontal=" true "/>    <webview        android:layout_width=" Wrap_ Content "        android:layout_height=" wrap_content "        android:id=" @+id/mwebview "        android:layout_below=" @+id/mbutton "        android:layout_centerhorizontal=" true "/></relativelayout>

Mainactivity.xml

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);        Set the Encoding Mwebview.getsettings (). Setdefaulttextencodingname ("Utf-8");        Support JS Mwebview.getsettings (). Setjavascriptenabled (True);        Set background color transparent Mwebview.setbackgroundcolor (COLOR.ARGB (0, 0, 0, 0)); Sets the local call object and its interface Mwebview.addjavascriptinterface (new JavascripTObject (This), "MYOBJ");        Loading Web page mwebview.loadurl ("file:///android_asset/test.html"); Click Invoke JS in Method Mbtn.setonclicklistener (new View.onclicklistener () {@Override public void onclic            K (View v) {mwebview.loadurl ("Javascript:funfromjs ()");    }        });        } Final class Javascriptobject {private Context mcontxt;        Public Javascriptobject (Context mcontxt) {this.mcontxt = Mcontxt; } @JavascriptInterface//sdk17 version above plus annotated public void funfromandroid (String name) {//This can be returned by JS data na        The ME operates Toast.maketext (Mcontxt, "Call Funfromandroid:" + Name, Toast.length_long). Show (); }    }}

Second, the local HTML dynamic add JS ibid first in the Assets folder has. html,. js files

Test.xml to remove <script></script> tags from their contents

<body><a href= "http://www.baidu.com" >js call local method </a><p></p><div id= "Helloweb" > </div></body>
Js.js with the 1th unchanged

function Funfromjs () {    myobj.fun1fromandroid ("First JS callback");}
Mainactivity.java

Need to read JS and add to WebView in order to achieve the effect of adding JS

Read JS added to String type

    JS text    private String Wholejs = "";

<span style= "White-space:pre" ></span>//get JS text        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 load Failed", Toast.length_short). Show ();            }        } catch ( IOException e) {            e.printstacktrace ();        }

WebView Add Read JS

Mwebview.loadurl ("javascript:" + Wholejs);


Mainactivity Complete code

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 MW    Ebview;    Private Button mBtn;    JS text 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);        Set the Encoding Mwebview.getsettings (). Setdefaulttextencodingname ("Utf-8"); Support JS Mwebview.getsettings (). SetjavascriptenaBled (true);        Set background color transparent Mwebview.setbackgroundcolor (COLOR.ARGB (0, 0, 0, 0));        Sets the local calling object and its interface Mwebview.addjavascriptinterface (new Javascriptobject (This), "MYOBJ");        Loading Web page mwebview.loadurl ("file:///android_asset/test.html"); Click Invoke JS in Method Mbtn.setonclicklistener (new View.onclicklistener () {@Override public void onclic            K (View v) {//Trigger JS Mwebview.loadurl in HTML ("Javascript:funfromjs ()");        }        });        Get js text 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 load Failed", Toast.length_short). Show ();        }} catch (IOException e) {e.printstacktrace ();    }//webview Add read JS Mwebview.loadurl ("javascript:" + Wholejs);        } Final class Javascriptobject {private Context mcontxt;        Public Javascriptobject (Context mcontxt) {this.mcontxt = Mcontxt; } @JavascriptInterface//sdk17 version above plus annotated public void funfromandroid (String name) {//This can be returned by JS data na        The ME operates Toast.maketext (Mcontxt, "Call Funfromandroid:" + Name, Toast.length_long). Show (); }    }}

Activity_main.xml with the 1th unchanged


6th, 7 will be in the next blog about interception and webview some common listening events


Android WebView and JS interaction (add JS dynamically)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.