Acquisition of the Robotium principle webelement elements

Source: Internet
Author: User
Tags tagname

The Robotium Framework supports WebView, getwebelements (), getwebelements (by), and other methods in Robotium to acquire WebView elements in Android and provides The Clickonwebelement method is used to complete the Click event. Native controls in Android are better captured, so how do you get the framework for WebView? The first step: using JS to get all the elements in the page on a PC, the elements that get the page can be done by injecting JavaScript elements, for example in Chrome, opening the tool--javascript console (shortcut: ctrl+shift+j), entering Javascript:prompt ( Document. URL) pops up a prompt with the URL of the current page, so you can display all of the page elements in this pop-up box by writing the appropriate JS script. Robotiumweb.js is the JS script for this feature implementation. Take the solo getwebelements () as an example,
Public Arraylist<webelement> getwebelements (Boolean onlysufficientlyvisible) {Boolean javascriptwasexecuted = Executejavascriptfunction ("allwebelements ();"); Return getwebelements (javascriptwasexecuted, onlysufficientlyvisible);}
Private Boolean executejavascriptfunction (final String function) {final WebView WebView = Viewfetcher.getfreshestview ( Viewfetcher.getcurrentviews (Webview.class, True)); if (WebView = = null) {return false;}                Do some preparation before JS injection, such as setting WebView to allow JS to be executed, and returning the script in Robotiumweb.js as a string to the final string javaScript = Prepareforstartofjavascriptexecution (); Activityutils.getcurrentactivity (false). Runonuithread (New Runnable () { public void Run () {if (WebView! = null) {Webview.loadurl ("javascript:" + JavaScript + function);}}); return true;}
It can be seen that this method executes the allwebelements () function, which is similar to executing the Robotiumweb.js file in the following JS code snippet:you can put the following snippet in the JavaScript console to see the effect
Javascript:function allwebelements () {for (var key in document.all) {try{promptelement (Document.all[key]);//    Call the Promptelement (element) function}catch (ignored) {}}finished (); After execution, call the finished () function}function promptelement (element) {var id = Element.id;var Text = element.innertext;if (Text.trim () . length = = 0) {text = Element.value;} var name = Element.getattribute (' name '); var className = Element.classname;var TagName = Element.tagname;var attributes = " "; var htmlattributes = Element.attributes;for (var i = 0, htmlattribute; Htmlattribute = Htmlattributes[i]; i++) {attributes + = Htmlattribute.name + "::" + htmlattribute.value;if (i + 1 < htmlattributes.length) {attributes + = "# $";}}  var rect = Element.getboundingclientrect (); if (rect.width > 0 && rect.height > 0 && rect.left >= 0  && rect.top >= 0) {prompt (id + ';, ' + text + ';, ' + name + ';, "+ ClassName +";, "+ TagName +";; "+ Rect.left + ';, ' + Rect.top + ';, ' + Rect.width + ';, ' + Rect.height + ';, ' + Attributes);    Popup}}function finished () {prompt (' robotium-finished ') that contains fields such as ID, text, name, etc. Popup box with robotium-finished string to identify script injection execution end}

it can be seen from the script that JS obtains the page element and also has a certain format processing, the addition of each element, the symbol, which is also in the later code to more easily parse. The last call to the script is the finished () function, which pops up a hint box containing robotium-finished. This step completes the page element acquisition, so how does the ToolTip contain content in Android?
Step Two: Get the information in the prompt prompt box in WebView in Androidin the Android WebKit package there is a webchromeclient class, the Onjsprompt method in this class is used to handle the webview of the prompt box, when there is a JS prompt box in WebView, the method is called back, String The message parameter contains the information in the prompt box, so Robotium writes a robotiumwebclient class that inherits from the Webchromeclient class. covered the onjsprompt.
onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
@Overridepublic Boolean onjsprompt (WebView view, string URL, String message,string defaultvalue, Jspromptresult R) {if (Me Ssage! = null && (Message.contains (";,") | | message.contains ("robotium-finished"))) {                        // If the prompt box contains the robotium-finished string, that is, the JS injection script execution is complete if (message.equals ("robotium-finished")) { Webelementcreator.setfinished (TRUE);} Else{webelementcreator.createwebelementandaddinlist (message, view);//The contents of the prompt box can be processed}r.confirm (); return true;} else {if (originalwebchromeclient! = null) {return originalwebchromeclient.onjsprompt (view, URL, message, DefaultValue, R); }return true;}}
In addition, the original WebView default is not allowed to execute JS, so you need to perform the firstEnablejavascriptandsetrobotiumwebclient method. Set javascriptenabled to True to set Webchromeclient to Robotiumwebclient
public void Enablejavascriptandsetrobotiumwebclient (list<webview> webviews, webchromeclient originalwebchromeclient) {this.originalwebchromeclient = originalwebchromeclient;for (Final WebView webview:webviews {if (WebView! = null) {Inst.runonmainsync (new Runnable () {public void run () {webview.getsettings (). Setjavascriptenabled (True); Webview.setwebchromeclient (robotiumwebclient);}});}}
Step Three: Store the messages in the prompt in the webelement Java Beanafter getting the message in the prompt prompt box, the next step is to parse the messages that have been processed with special formatting, and then get the webelement ID, text, name, and so on.
Private Webelement createwebelementandsetlocation (String information, WebView WebView) {string[] data =            Information.split (";,"); The message is pressed;, the symbol is split, wherein;, the symbol is added in the previous JS when the string[] elements = null;int x = 0;int y = 0;int width = 0;int height = 0; hashtable<string, string> attributes = new hashtable<string, string> (); try{x = Math.Round (float.valueof ( Data[5]); y = Math.Round (float.valueof (data[6)); width = Math.Round (float.valueof (data[7])); height = Math.Round ( Float.valueof (Data[8])); elements = Data[9].split ("\\#\\$");} catch (Exception ignored) {}if (elements! = null) {for (int index = 0; index < elements.length; index++) {string[] Element = Elements[index].split ("::"); if (Element.length > 1) {attributes.put (element[0], element[1]);} else {attributes.put (element[0], element[0]);}}} Webelement webelement = null;try{webelement = new Webelement (data[0], data[1], data[2], data[3], data[4], attributes);//Will The ID, text, name and other fields are deposited in setlocation (Webelement, WebView, x, y, width, height);} CatchException ignored) {}return webelement;} 
/** * Sets  The location of a {@code webelement} * * @param webelement the {@code TextView} object to set location * @param webView  The {@code WebView} The text is shown in * @param x the x location to set * @param y the y location to set * @param width  The width to set * @param height of the height to set */private void setlocation (webelement webelement, WebView WebView, int x, int y, int width, int height) {Float scale = Webview.getscale (); int[] Locationofwebviewxy = new Int[2];webview.getloca Tiononscreen (LOCATIONOFWEBVIEWXY); int locationx = (int) (Locationofwebviewxy[0] + (x + (Math.floor (WIDTH/2))) * scale); NT Locationy = (int) (locationofwebviewxy[1] + (y + (Math.floor (HEIGHT/2)) * scale); Webelement.setlocationx (Locationx); Webelement.setlocationy (locationy);} 
at this point, the Webelement object contains fields such as ID, text, name, and x, y coordinates, and when you know the coordinates, you can send click events based on coordinates like native view in other Android.

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.