Let Java and JavaScript interact

Source: Internet
Author: User

This post is for reference from: Http://droidyue.com/blog/2014/09/20/interaction-between-java-and-javascript-in-android/

When we use WebView, we can let the Java code and the JavaScript code in the Web page interact, this article simply explains how the two interact.

One, JS call Java code

1.1 The Code of the Web page:

< HTML > <  type= "Text/javascript">    function toastmessage (message) {        Window.control.toastMessage (Message)    }    function Sumtojava (number1, number2) {       Window.control.onSumResult (Number1 + number2)    }</script>  Java-javascript Interaction in Android</html>

Can see, this page code has JS code, the main code snippet is as follows:

    function  toastmessage (message) {        window.control.toastMessage (message)    }      function  Sumtojava (Number1, number2) {       + number2)    }

One way to find out here: window.control.xxxxx. Here the control needs to be implemented on the Android side, the Web page only need to call on the line.

The invocation format is:window.jsInterfaceName.methodName (parametervalues) In this example we are using control as the injected interface name, so it becomes:

Window.control.toastMessage (Message)

1.2 Android Terminal

 PackageCom.example.javajsinteractiondemo;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.Menu;ImportAndroid.webkit.JavascriptInterface;Importandroid.webkit.WebChromeClient;Importandroid.webkit.WebSettings;ImportAndroid.webkit.WebView;Importandroid.webkit.WebViewClient;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {Private Static FinalString LogTag = "Mainactivity"; @SuppressLint ("Javascriptinterface") @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main);
FinalWebView Mywebview =(WebView) Findviewbyid (R.id.mywebview); WebSettings Settings=mywebview.getsettings (); Settings.setjavascriptenabled (true); Mywebview.addjavascriptinterface ( new Jsinteration (), "Control"); Mywebview.setwebchromeclient (Newwebchromeclient () {}); Mywebview.loadurl ("File:///android_asset/js_java_interaction.html"); } Public class jsinteration {@JavascriptInterface Public voidtoastmessage (String message) {Toast.maketext (Getapplicationcontext (), message, Toast.length_long). Show (); } @JavascriptInterface Public voidOnsumresult (intresult) {log.i (LogTag,"Onsumresult result=" +result); } }}

you can see that the webview is used in the addjavascriptinterface method defines an injection interface and class: Control & Jsinteration. Then after the jsinteration to write the implementation of the method: Toastmessage & Onsumresult, so in the JS call when Android will know what is the method of JS.

Second, Java calls JS

The method of invoking JS is very simple and the loading page is exactly the same

Basic format: Webview.loadurl ("Javascript:methodname (parametervalues)")

Example 1:

No parameter method

String call = "Javascript:sayhello ()"; Webview.loadurl (call);

Example 2:

Note that you need to escape double quotes for a string as a parameter value

String call = "Javascript:alertmessage (\" "+" content "+" \ ")", Webview.loadurl (call);

For information on how to safely interact and avoid injection attacks, please refer to: http://mobile.51cto.com/aprogram-452011.htm

For information on how to get the return value of JS, please refer to: Http://droidyue.com/blog/2014/09/20/interaction-between-java-and-javascript-in-android/

Let Java and JavaScript interact

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.