How to get xPath from html page (WebView) - java

How to determine the XPATH of an element at html page, opened in CrossWalkView(WebView) by onTouch event?

Problem was solved by using JS.
JS solution i got here:
I'm storing click coordinates in my db and then reloading them later and showing them on the site where the click happened, how do I make sure it loads in the same place?
InputStream is = getResources().openRawResource(R.raw.get_xpath);
Scanner s = new Scanner(is).useDelimiter("\\A");
String javascript = s.hasNext() ? s.next() : "";
myWebView.evaluateJavascript(javascript, null);
and here`s my JS code:
document.onclick= function(event) {
if (event===undefined) event= window.event; // IE hack
var target= 'target' in event? event.target : event.srcElement; // another IE hack
var root= document.compatMode==='CSS1Compat'? document.documentElement : document.body;
var mxy= [event.clientX+root.scrollLeft, event.clientY+root.scrollTop];
var path= getPathTo(target);
var txy= getPageXY(target);
alert('Clicked element '+path+' offset '+(mxy[0]-txy[0])+', '+(mxy[1]-txy[1]));
}
function getPathTo(element) {
if (element.id!=='')
return 'id("'+element.id+'")';
if (element===document.body)
return element.tagName;
var ix= 0;
var siblings= element.parentNode.childNodes;
for (var i= 0; i<siblings.length; i++) {
var sibling= siblings[i];
if (sibling===element)
return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
if (sibling.nodeType===1 && sibling.tagName===element.tagName)
ix++;
}
}
function getPageXY(element) {
var x= 0, y= 0;
while (element) {
x+= element.offsetLeft;
y+= element.offsetTop;
element= element.offsetParent;
}
return [x, y];
}

Related

How to use Jsoup to get href link without the extra characters?

I have an Element list of which i'm using jsoup's method attr() to get the href attribute.
Here is part of my code:
String searchTerm = "tutorial+programming+"+i_SearchPhrase;
int num = 10;
String searchURL = GOOGLE_SEARCH_URL + "?q="+searchTerm+"&num="+num;
Document doc = Jsoup.connect(searchURL).userAgent("chrome/5.0").get();
Elements results = doc.select("h3.r > a");
String linkHref;
for (Element result : results) {
linkHref = result.attr("href").replace("/url?q=","");
//some more unrelated code...
}
So for example, when i use the search prase "test", the attr("href") produces (first in the list):
linkHref = https://www.tutorialspoint.com/software_testing/&sa=U&ved=0ahUKEwi_lI-T69jTAhXIbxQKHU1kBlAQFggTMAA&usg=AFQjCNHr6EzeYegPDdpHJndLJ-889Sj3EQ
where i only want: https://www.tutorialspoint.com/software_testing/
What is the best way to fix this? Do i just add some string operations on linkHref (which i know how) or is there a way to make the href attribute contain the shorter link to begin with?
Thank you in advanced
If you always want to remove the query parameters you can make use of String.indexOf() e.g.
int lastPos;
if(linkHref.indexOf("?") > 0) {
lastPos = linkHref.indexOf("?");
} else if (linkHref.indexOf("&") > 0){
lastPos = linkHref.indexOf("&");
}
else lastPos = -1;
if(lastPos != -1)
linkHref = linkHref.subsring(0, lastPos);

how to set html node value using webview with javafx

i am trying to set the value of the html form elements after loaded into webview.I tried to set using
org.w3c.dom.Document doc = webEngine.getDocument();
HTMLFormElement form = (HTMLFormElement) doc.getElementsByTagName("form").item(0);
NodeList nodes = form.getElementsByTagName("input");
nodes.item(1).setNodeValue("yadayada"); //this is where i am setting the value
but no success. can anybody help me out. here is my code.
org.w3c.dom.Document doc = webEngine.getDocument();
if (doc!=null && doc.getElementsByTagName("form").getLength() > 0) {
HTMLFormElement form = (HTMLFormElement) doc.getElementsByTagName("form").item(0);
String username = null;
String password = null;
NodeList nodes = form.getElementsByTagName("input");
for (int i = 0; i < nodes.getLength(); i++) {
if(nodes.item(i).hasAttributes()){
NamedNodeMap attr = nodes.item(i).getAttributes();
for (int j=0 ; j<attr.getLength();j++){
Attr atribute = (Attr)attr.item(j);
if(atribute.getValue().equals("password")){
System.out.println("Password detected");
nodes.item(i).setNodeValue("123456");
}
}
}
}
}
i found the solution after surfing the web. The problem was i was using set node value but values of input tags are set using HTMLInputElement.This link was valuabe for me
Performing an automated form post of login using webview
for example
HTMLInputElement password = (HTMLInputElement) nodes.item(0).setValue("yadayada");

Android browser doesn't work with geolocation

I am building a website which use geolocation code, It suppose to load mapCanvas and after user click on "Finde Me!" button get his location and set a center of a map based on user location. It's working fine with Firefox, Chrome, Safari, tested on regular PC and iPhone the only device doesn't work with it is any mobile phone with Android. here is a code:
<script src="http://maps.google.com/maps?file=api&v=3&key=YourKey"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(17, 25);
iconBlue.shadowSize = new GSize(1, 1);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(17, 25);
iconRed.shadowSize = new GSize(1, 1);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["restaurant"] = iconBlue;
customIcons["bar"] = iconRed;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(50.061795,19.936924), 16);
// Change this depending on the name of your PHP file
GDownloadUrl("Your_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
function findLoc(){
if (!navigator.geolocation) {
alert('Sorry, your browser does not support Geo Services');
}
else {
// Get the current location
navigator.geolocation.getCurrentPosition(showMap);
}
}
function showMap(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var myPoint = new GLatLng(lat, lon);
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(myPoint, 15);
GDownloadUrl("Your_xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, name, address, type);
map.addOverlay(marker);
}
});
function createMarker(point, name, address, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
}
I couldn't find any solution to make it work.
PS
There is no errors or statements giving any hint making it more understandable.
Device got GPS enable.
pleas help I've been trying to figure it out for 2 weeks
I'm afraid you just have an arduous old-fashioned debug in front of you. My approach would be to add visible output at various important points in the code (just before and after getCurrentPosition is called, and at the beginning of showMap, for instance) and narrow down from there just where the failure is occurring. Once you know what's failing you can probably develop an idea of why, but until you know that you're flailing in the dark.
(I've worked on a geolocation-based mobile webapp that supported Android, so in case you need any reassurance, there's nothing inherently impossible about your situation.)

Syncing text and audio with jQuery/javascript, more efficiently?

I've been syncing some text with audio, using jPlayer and jQuery's .fadeIn/.fadeOut. It works as expected, using these if statements:
var currentTime = Math.floor(event.jPlayer.status.currentTime)
if (currentTime > 1){
$("#slide1").fadeIn("fast");
} else if (currentTime < 1){
$("#slide1").fadeOut("fast");
}
if (currentTime >= 9 && currentTime < 49){
$("#slide2").fadeIn("fast");
} else if (currentTime < 9){
$("#slide2").fadeOut("fast");
}
and so on. This will show/hide div's at the proper time and allow for scrubbing. The code I have adapted is from here. I am a designer who knows a little programming, so my skills aren't great but I understand a lot. I'm looking for a more efficient way to do this, instead of copy/pasting the if statement as there will be A LOT of them. Possibly an array of all the in/out times? I'm not sure how to do it.
Best case scenario would be to have an xml list of times control prebuilt divs (I think anyway). Any ideas on how to do it?
Thanks for your time,
S
Update
Ok, I've made some progress, but am having problems with the XML/loop. I have added content to the XML and have it dynamically generating divs. Here is the xml:
<?xml version="1.0" encoding="utf-8" ?>
<Slides>
<Slide id="#slide1" in="1" out="9999" content="Implications"></Slide>
<Slide id="#slide2" in="9" out="49" content="Implications have the form"></Slide>
<Slide id="#slide3" in="11" out="49" content="If A is true, then B is true."></Slide>
</Slides>
and here is my code that creates the divs (that are hidden)
<script>
var mySlides = [];
$.ajax({
type: "GET",
url: "xml.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml)
{
$(xml).find("Slide").each(function() {
$("#slides").append("<div class=\"starthidden\" id=" + $(this).attr("id") + ">" + $(this).attr("content") + "</div>");
});
var $slides = xml.find('Slide');
for (var i = 0, len = $slides.length; i < len; i++) {
mySlides[mySlides.length] = {
in : $slides.eq(i).attr('in'),
out : $slides.eq(i).attr('out')
};
}
}
$("#audio").bind($.jPlayer.event.timeupdate, function(event) {
var currentTime = Math.floor(event.jPlayer.status.currentTime)
for (var i = 0; i < len; i++) {
if (currentTime >= mySlides[i].in && currentTime < mySlides[i].out) {
$(mySlides[i].id).fadeIn("fast");
} else if (currentTime < mySlides[i].in) {
$(mySlides[i].id).fadeOut("fast");
}
}
});
</script>
I guess I just don't really know where to go from here to get the divs to show/hide now? As well, I've got to figure out a way to turn many divs off as well, as slides are actually lines, not full slides so I need to clear them off the stage (if you see in the XML, it would be at 49sec). Can anyone help? Thanks so much.
S
You can setup an array of objects that store information for each slide.
//setup an array of objects that store information for each caption
var mySlides = [
{
id : '#slide1',//set a string reference to the element to fade
in : 1,//start time
out : 9999//end time (this is long so it doesn't fade out ever)
},
{
id : '#slide2',
in : 9,
out : 49
}
], len = mySlides.length;
//loop through the slides to check if they should be faded in/out
for (var i = 0; i < len; i++) {
if (currentTime >= mySlides[i].in && currentTime < mySlides[i].out) {
$(mySlides[i].id).fadeIn("fast");
} else if (currentTime < mySlides[i].in) {
$(mySlides[i].id).fadeOut("fast");
}
}
Update
If your XML file is something like this:
<slides>
<slide id="#slide1" in="1" out="9999"></slide>
<slide id="#slide2" in="9" out="49"></slide>
</slides>
Then you can grab the XML file using AJAX and parse it for it's data like this:
var mySlides = [];
$.ajax({
url : 'path/to/file.xml',
type : 'get',
dataType : 'xml',
success : function (serverResponse) {
var $slides = serverResponse.find('slide');
for (var i = 0, len = $slides.length; i < len; i++) {
mySlides[mySlides.length] = {
id : $slides.eq(i).attr('id'),
in : $slides.eq(i).attr('in'),
out : $slides.eq(i).attr('out')
};
}
}
});
with your page content i would include some JSON (using Japser's structure, forget XML) detailing the messages and their in/out points..
then, in a handler for jPlayer's timeupdate event (called every 250ms), examine event.jPlayer.status.currentTime and determine which message from your JSON should currently be displayed.

how can i get data out of DIV using html parser in java

i am using Java html parser(link text) to try to parse this line.
<td class=t01 align=right><div id="OBJ123" name=""></div></td>
But I am looking for the value like I see on my web browser, which is a number. Can you help me get the value?
Please let me know if you need more details.
Thanks
From the documentation, all you have to do is find all of the DIV elements that also have an id of OBJ123 and take the first result's value.
NodeList nl = parser.parse(null); // you can also filter here
NodeList divs = nl.extractAllNodesThatMatch(
new AndFilter(new TagNameFilter("DIV"),
new HasAttributeFilter("id", "OBJ123")));
if( divs.size() > 0 ) {
Tag div = divs.elementAt(0);
String text = div.getText(); // this is the text of the div
}
UPDATE: if you're looking at the ajax url, you can use similar code like:
// make some sort of constants for all the positions
const int OPEN_PRICE = 0;
const int HIGH_PRICE = 1;
const int LOW_PRICE = 2;
// ....
NodeList nl = parser.parse(null); // you can also filter here
NodeList values = nl.extractAllNodesThatMatch(
new AndFilter(new TagNameFilter("TD"),
new HasAttributeFilter("class", "t1")));
if( values.size() > 0 ) {
Tag openPrice = values.elementAt(OPEN_PRICE);
String openPriceValue = openPrice.getText(); // this is the text of the div
}

Categories

Resources