I am trying to load a page and then run a javascript code on it, I found a Greasemonkey script that does the same, but I am having problems implementing the same thing in android, probably because I don't know anything about javascript.
This is the Greasemonkey script; it's supposed to a give a new link:
window.addEventListener("load", function ()
{
var link = document.evaluate("//div[@class='dl_startlink']/div/a[contains(@href,'"+window.location.href.match(/\?(.*)$/)[1]+"')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
if( !link.snapshotLength )
return;
location.href = link.snapshotItem(0).href;
}, false);
and this is how I want to run it:
public void onPageFinished (WebView view, String url) {
System.out.println("webview loaded");
webView.loadUrl("javascript:/*...........Javascript code here........*/");
}
Any ideas on how I get that link and load that page in the webview? EDIT: Another version does the same thing.
var candidates = document.evaluate("//*[@class = 'dl_startlink']/div", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
if( !candidates.snapshotLength )
return;
//The DIV with the highest zIndex has the *real* link; the rest are useless.
- var maxDiv = candidates.snapshotItem(0);
- for( var i = 1; i < candidates.snapshotLength; i++ )
- if( maxDiv.style.zIndex < candidates.snapshotItem(i).style.zIndex )
- maxDiv = candidates.snapshotItem(i);
- location.href = maxDiv.children[0].href;
Ok, here's only simple Xpath query, which may be rewritten as CSS selector.
Also I decided to replace window.location.href.match(/\?(.*)$/)[1]
. If my version will not work, replace first 2 lines with var query = window.location.href.match(/\?(.*)$/)[1];
.
Actually, maybe even var query = window.location.search.replace(/^\?/,'')
is enough.
window.addEventListener("load", function ()
{
var l = window.location;
var query = l.search ? (l.search.replace(/^\?/,'') + l.hash) : ""
var link = document.querySelector("div.dl_startlink > div > a[href='" + query + "']");
if (!link) return;
l.href = link.href;
}, false);
New code for Android:
var candidates = document.querySelector("div.dl_startlink > div");
if( !candidates.length)
return;
//The DIV with the highest zIndex has the *real* link; the rest are useless.
var maxDiv = candidates[0];
for( var i = 1; i < candidates.length; i++ )
if( maxDiv.style.zIndex < candidates[i].style.zIndex )
maxDiv = candidates[i];
location.href = maxDiv.children[0].href;
Compacted version:
webView.loadUrl("javascript:window.addEventListener('load',function(){var%20candidates=document.querySelector('div.dl_startlink>div');if(!candidates.length)return;var maxDiv=candidates[0];for(var%20i=1;i<candidates.length;i++)if(maxDiv.style.zIndex<candidates[i].style.zIndex)maxDiv=candidates[i];location.href=maxDiv.children[0].href;},false)");