Android WebView and JS interaction

Source: Internet
Author: User

The first step:

Adding network permissions in Mainfest.xml

<use-permission android:name= "Android.permission.INTERNET"/>

If you're accessing local, you don't need to add this permission.

Step Two:

Load the locally written HTML file (define the method Funfromjs () provided to Android in JS, and the object interface Android provides to the JS call) fun1fromandroid (String name), placed in the assets directory.

eg.

<body>

Calling local methods in <a>js </a>

<script>

function Funfromjs () {

document.getElementById ("Helloweb"). Innerhtml= "Hellowebview,i ' m from JS";

}

var aTag = document.getElementsByTagName (' a ') [0];

Atag.addeventlistener (' click ', function () {

Call the Android Local method

Myobj.fun1fromandroid ("Call Android native method Fun1fromandroid (String name)!! ");

return false;

}, False);

</script>

<p></p>

<div id= "Helloweb" >

</div>

</body>

Step Three:

Implementing the code for Android Engineering and JS Interaction

Android Theme Code:

eg.

@SuppressLint ({"Javascriptinterface", "setjavascriptenabled"})

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

Initialization

Initviews ();

Set encoding

Mwebview.getsettings (). Setdefaulttextencodingname ("Utf-8");

Support JS

Mwebview.getsettings (). Setjavascriptenabled (True);

Set Background color transparency

Mwebview.setbackgroundcolor (Color.argb (0, 0, 0, 0));

Set local call objects and their interfaces

Mwebview.addjavascriptinterface (New Javascriptobject (Mcontext), "MYOBJ");

Loading JS

Mwebview.loadurl ("file:///android_asset/test.html");

Click Invoke JS in the method

Mbtn1.setonclicklistener (New View.onclicklistener () {

@Override

public void OnClick (View v) {

Mwebview.loadurl ("Javascript:funfromjs ()");

Toast.maketext (Mcontext, "Call Javascript:funfromjs ()", Toast.length_long). Show ();

}

});

}

JS calls the Android object method definition

public class Javascriptobject {

Context Mcontxt;

@JavascriptInterface//sdk17 version plus annotations

Public Javascriptobject (Context mcontxt) {

This.mcontxt = Mcontxt;

}

public void Fun1fromandroid (String name) {

Toast.maketext (mcontxt, Name, Toast.length_long). Show ();

}

public void Fun2 (String name) {

Toast.maketext (Mcontxt, "Call Fun2:" + Name, Toast.length_short). Show ();

}

}

Note: Api16 needs to be annotated on the calling local method later @javascriptinterface

"Precautions"

The license "Android.permission.INTERNET" must be used in 1.androidmanifest.xml, otherwise the Web page not available error will occur.

2. If there is JavaScript on the page visited, the WebView must be set to support JavaScript. Webview.getsettings (). Setjavascriptenabled (True);

3. If the page links, if you want to click on the link to continue in the current browser response, instead of the new Android system browser should link in the ring, you must overwrite the WebView Webviewclient object.

4. For 1th, if the Android SDK is used to provide a schema, the prefix is "file:///android_asset/". WebView encounters such a schema, it will load the resources under the assets directory. such as "file:///android_asset/demo.html", you do not have to use the license "Android.permission.INTERNET".

    • WebView Open JavaScript Script execution
    • WebView sets the interface for JavaScript calls.
    • The client and the Web side write code that calls each other.
    • Java and JS interactions have the following features:

1.Java Call JS inside the function, the speed is not satisfactory, about one hundred or two hundred milliseconds at a time, if you want to do a very interactive thing, this speed will make people crazy. And the reverse is not the same, JS to tune the Java method, fast, basically 40-50 milliseconds at a time. So try to use JS to call the Java method, rather than Java to invoke the JS function.

2.Java Call JS function, no return value, and JS call Java method, can have a return value. The return value can be a base type, a string, or an object. If it's a string, there's a nasty question, and 3rd I'll talk about. If it is an object, the object will be converted to a JS object, which can be accessed directly inside the method. But I do not recommend that Java be returned to JS is the object, unless it is necessary. Because JS receives objects returned by Java, there are some swap objects, and if the number of these objects increases to 500 or more than 600, the program will have problems. So try to return the base data type or string.

3.Js call Java method, the return value if it is a string, you will find that the string is native, you can not make some modifications to it, such as want to substr it, not to be taken. How to fix it? Turn into locale. You can use the toLocaleString () function. However, this function is not fast enough, and it can be time-consuming to convert many strings.

Webviewclient mainly helps WebView to handle various notifications, request events, such as:

    • Onloadresource
    • Onpagestart
    • Onpagefinish
    • Onreceiveerror, etc.

Webchromeclient main Auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress and so on such as:

    • Onclosewindow (Close WebView)
    • Oncreatewindow ()
    • Onjsalert (WebView on alert is invalid and requires custom Webchromeclient processing popup)
    • Onjsprompt
    • Onjsconfirm
    • Onreceivedtitle, etc.

A simple Demo

Android WebView and JS interaction

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.