[Android] WebView and JS Interaction

Source: Internet
Author: User

Get WebView Object

Call the getsettings () method of the WebView object to get the websettings Object

Call the setjavascriptenabled () method of the websettings object , set js available, Parameters: Boolean

When judging whether to support JS , do not use alert (), the default does not work, you can first use document.write () test

Call the addjavascriptinterface (obj, InterfaceName) method of the WebView object to add js interface, Parameters: Object objects, String Interface Name (This object is in the JS aliases in the

Define an inner class Myjavascript

Define a Method Showtoast (), show toast,API version greater than + need to annotate @ Javascriptinterface

Java Code:

 PackageCom.tsh.mywebview;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.app.ProgressDialog;ImportAndroid.graphics.Bitmap;ImportAndroid.os.Bundle;Importandroid.view.KeyEvent;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.Window;ImportAndroid.webkit.JavascriptInterface;Importandroid.webkit.WebSettings;ImportAndroid.webkit.WebView;Importandroid.webkit.WebViewClient;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateWebView WebView; PrivateProgressDialog PD; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);                Setcontentview (R.layout.activity_main); PD=NewProgressDialog ( This); Pd.setmessage ("Loading ..."); //simple settings for WebViewwebview=(WebView) Findviewbyid (r.id.wv_internet); //http://100.65.187.106/test.phpWebview.loadurl ("http://100.65.187.106/test.php"); WebSettings websettings=webview.getsettings (); Websettings.setsupportzoom (true); Websettings.setbuiltinzoomcontrols (true); //JS Interaction        NewMyjavascript (). Showtoast ("111"); Websettings.setjavascriptenabled (true); Webview.addjavascriptinterface (NewMyjavascript (), "Android"); Webview.loadurl ("Javascript:documentwrite (' Test ')"); Webview.setwebviewclient (Newwebviewclient () {@Override Public voidonpagestarted (WebView view, String URL, Bitmap favicon) {pd.show (); } @Override Public voidonpagefinished (WebView view, String URL) {Pd.dismiss ();            }        }); }    //function interface exposed to JS     Public classmyjavascript{//Show Toast//if target is greater than or equal to API 17, you need to add the following annotations@JavascriptInterface Public voidshowtoast (String text) {Toast.maketext (mainactivity. This, text, 1). Show (); }        //Show Loading@JavascriptInterface Public voidShowprogressdialog (String text) {pd.setmessage (text);        Pd.show (); }    }    //back Key@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {        if(keycode==keyevent.keycode_back&&Webview.cangoback ())            {Webview.goback (); return true; }        return Super. OnKeyDown (KeyCode, event); }    //Menu Key@Override Public BooleanOncreateoptionsmenu (Menu menu) {menu.add (0, 0, 0, "refresh"); Menu.add (0, 0, 1, "Back"); Menu.add (0, 0, 2, "forward"); return Super. Oncreateoptionsmenu (menu); }    //Menu click events@Override Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getorder ()) { Case0: Webview.reload ();  Break;  Case1:            if(Webview.cangoback ()) {webview.goback (); }             Break;  Case2:            if(Webview.cangoforward ()) {Webview.goforward (); }             Break; }        return Super. onoptionsitemselected (item); }}

JS Code:

<HTML><Head>    <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/>    <title>Test Android Program</title></Head><Body>test Android and JS interaction<BR/>    <ButtonOnClick= "Showtoast ()">Show Toast</Button>    <BR/>    <ButtonOnClick= "Showprogressdialog ()">Show loading</Button><Scripttype= "Text/javascript">functionShowtoast () {Android.showtoast ("Show Toast");}functionShowprogressdialog () {Android.showprogressdialog ("Show progress bar");}</Script></Body></HTML>

[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.