Android WebView and JS interaction

Source: Internet
Author: User

Project to use WebView and JS interaction, check the previous project feel or it is necessary to tidy up.
Simple description of the use of the project under the place, for example, in the Web page need to log in place to click the login to go to the app native login interface to log in, click on the Web page call pop-up native dialog asked whether to call, click on the image inside the Web page to enlarge processing. For the above requirements, we have a common way of two, one is to listen to a tag, in shouldoverrideurlloading according to the URL to judge, the second is the JS code injection, find we want to deal with the elements of JS code injection. Here's a simple description of both of these ways
First you need to initialize the WebView and set up support JavaScript, there are several common configuration properties, you can add in the project according to requirements

WebSettings websetting=WebView.GetSettings ();//Support JavaScriptWebsetting.Setjavascriptenabled (true);//settings can access the file sWebsetting.Setallowfileaccess (true);//Tell JavaScript to come from the open window. This applies to the JavaScript function's window, open (). Websetting.Setjavascriptcanopenwindowsautomatically (true);//Support scalingWebsetting.Setsupportzoom (true);//Whether the Network load data is forbiddenWebsetting.Setblocknetworkloads (false);//Set whether multiple windows are supportedWebsetting.Setsupportmultiplewindows (true);//whether to turn on local DOM storageWebsetting.Setdomstorageenabled (true);//settings not cachedWebsetting.Setcachemode (websettings.Load_no_cache);//block loading picturesWebsetting.Setblocknetworkimage (false);//Support Enable pluginWebsetting.Setpluginstate (websettings.Pluginstate. on);//Set any comparison zoom to TrueWebsetting.Setusewideviewport (true);//Set WebView mode for loading pagesWebsetting.Setloadwithoverviewmode (true);//Control page display layout //Narrow_columns: The width of all columns does not exceed the width of the screen if possible //Normal: show no rendering //single_column: Enlarge All content in a column webview equal widthWebsetting.Setlayoutalgorithm (websettings.Layoutalgorithm.Narrow_columns);//Prohibit geo-targetingWebsetting.Setsaveformdata (true);//Whether to start geo-locationWebsetting.Setgeolocationenabled (true);//Set the location of the database pathWebsetting.Setgeolocationdatabasepath ("/data/data/org.itri.html5webview/databases/");

Next is the two classes webviewclient and webchromeclientthat are very important in webview interactions. Webviewclient is to help WebView handle various notifications, request events, specifically including the following common methods:

onLoadResource()// 在加载页面资源时会调用,每一个资源(比片)的加载都会调用一次。    //在点击请求的是链接是才会调用,重写此方法返回true表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边。这个函数我们可以做很多操作,比如我们读取到某些特殊的URL,于是就可以不打开地址,取消这个操作,进行预先定义的其他操作,这对一个程序是非常必要的。onPageStart   //这个事件就是开始载入页面调用的,通常我们可以在这设定一个loading的页面,告诉用户程序在等待网络响应。 onPageFinish  //在页面加载结束时调用。同样道理,我们知道一个页面载入完成,于是我们可以关闭loading 条,切换程序动作。 onReceiveError  // (报告错误信息) onReceivedHttpAuthRequest   )//(获取返回信息授权请求) 

Webchromeclient is the Auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress, etc., commonly used methods have the following several:

onCloseWindow()   //关闭WebViewonCreateWindow()   //WebView上alert是弹不出来东西的,需要定制你的WebChromeClient处理弹出)  onJsPrompt   onJsConfirm   onProgressChanged  //可以根据加载进度设置进度条onReceivedIcon  //可以获取URL icononReceivedTitle  //可以获取URL title

First, monitor a tag
This implementation is relatively simple, we can in the shouldoverrideurlloading based on the URL to judge, such as the interface has a call function, its JS code is as follows

Here we can pop the native dialog by the following way

 public   Boolean  shouldoverrideurlloading  (WebView view, String URL) {if  (textutils.isempty (URL)) return  true ; if  (Url.startswith ( "tel:" )) {Phonedialog Calldialog = new  phonedialog (webviewactivity.this , URL);                Calldialog.disdialog ();                Calldialog.callphone ();                Calldialog.show (); return             true ;        } return  true ; }

Second, through the JS code
There are two kinds of commonly used injection methods, the first is when the webview loaded, read the entire JS file content, and then the entire file content in the form of a string, through Webview.loadurl ("javascript:filecontentstring" ), but I don't seem to have used it much. This is generally the second way to meet business needs by setting events to specific tags.
For example, we give all the pictures to set a click event to get pictures, do some of the columns to enlarge the storage, etc., we can be implemented by the following code.

 //Inject JS function to monitor    Private void Addimageclicklistner() {The function of this JS function is to iterate through all the IMG points and add the onclick function, which is the function of invoking the local Java interface and passing the URL when the image is clicked.Webview.loadurl ("javascript: (function () {"+"var objs = document.getElementsByTagName (\" img\ "); "+"for (var i=0;i<objs.length;i++)"+"{"+"Objs[i].onclick=function ()"+"    {  "+"Window.imagelistner.openImage (THIS.SRC); "+"    } "+"}"+"}) ()"); }//JS Communication interface     Public  class javascriptinterface {        PrivateContext context; Public Javascriptinterface(Context context) { This. Context = Context; }@android. WebKit. Javascriptinterface Public void Openimage(String img)        {Toast.maketext (Context,img,toast.length_short). Show (); }    }//The two methods above are implemented to add a click event to a picture, we also need to set the WebView and inject @SuppressLint({"Javascriptinterface","Newapi"})@Override         Public void onpagefinished(WebView view, String URL) {view.getsettings (). setjavascriptenabled (true);Super. onpagefinished (view, URL); Addimageclicklistner ();after the page load is completed, add the Click JS function of the listening image}//Set the WebViewWebview.addjavascriptinterface (NewJavascriptinterface ( This),"Imagelistner");

The above implementation method has the following points to note: 1, note here the method name Imagelistener and input JS code inside the method consistent, 2, Custom method Openimage Be sure to indicate @android.webkit.javascriptinterface, otherwise it will not work.
We can see that the JS code we inject is to get all the IMG elements through getElementsByTagName and then set the click events, and if we set up a specific element, we can get a separate element by getElementById. Alternatively, the element can be obtained by getelementsbytagname based on the tag.

This is the way I know at this stage, if there are other better ways to implement it can be discussed together.

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.