How to Convert this Greasemonkey code to JavaScript for Android? - javascript

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)");

Related

Generation unique url after redirect Contact Form 7

i use this code
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'https://www.example.com/thank-you/';
}, false );
</script>
This code redirect me https://www.example.com/thank-you/
I want this redirect me https://www.example.com/thank-you/fdsffdfggfh (unique link everytime) but show me
https://www.example.com/thank-you/ this page content.
I try this and this work
document.addEventListener( 'wpcf7mailsent', function( event ) {
var length = 10;
var res = '';
var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
var charLen = chars.length;
for ( var i = 0; i < length; i++ ) {
res += chars.charAt(Math.floor(Math.random() * charLen));
}
location = 'http://example.com/thank-you/?'+res;
}, false );
thanks you #pagalprogrammer
You can do this easily by adding following code snippet on the target page:
function random_string(length) {
var res = '';
var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
var charLen = chars.length;
for ( var i = 0; i < length; i++ ) {
res += chars.charAt(Math.floor(Math.random() * charLen));
}
return "/"+res;
}
window.history.pushState("", "", window.location.href+random_string(10));
You can also put some other random string function. This code make use of History API
https://www.example.com/thank-you/fdsffdfggfh will end up in server routing. so you'll need to configure your server (nginx etc.) to redirect these requests to https://www.example.com/thank-you.
Another approch:
you can use query params - https://www.example.com/thank-you?YOUR_KEY=fdsffdfggfh
or hash https://www.example.com/thank-you#fdsffdfggfh

Why isn't my `load` function getting called?

I'm trying to preload certain images that I have decorated with an attribute and I'm wondering if you guys can help me figure out what's going wrong here. I have
var barlen = $('#SSWEprogressbar').width(),
$elems = $('[data-srcurl]'),
n = $elems.length;
for ( var k = 0; k < n; ++k )
{
var $elem = $($elems[k]);
var img = new Image(),
url = $elem.attr('data-srcurl');
$(img).load(function(){
console.log("we're here");//TEST
$('#SSWEloaderfront').attr('src',url);
$('#SSWEloadprogress').width(k/n*barlen + "px");
});
var srctgt = $elem.attr('data-srctgt');
if ( srctgt == "srcattr" )
{
$elem.attr('src',url);
}
else if ( srctgt == "bgimg" )
{
$elem.css('background-image',url);
}
}
and then
console.log("we're here");//TEST
isn't being invoked. Any ideas?
You aren't setting the src attribute on the img element, so the load will never fire. You need to add $(img).attr('src', url);

Redirecting multiple values in URL with Greasemonkey

I'm trying to get Greasemonkey to automatically redirect a page when it hits a certain URL, and redirect to a page with two of the same values. For instance:
http://www.google.com/page=438985&view=49834
into: http://www.google.com/document/page=438985/field&view=49834&DONE
I've tried the following:
var links,thisLink;
links = document.evaluate("//a[#href]",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
for (var i=0;i<links.snapshotLength;i++) {
var thisLink = links.snapshotItem(i);
thisLink.href = thisLink.href.replace(RegExp('http://www.google.com/page=($1)&view=($2)'),
'http://www.google.com/document/page=$1/field&view=$2&DONE');
}
var links = document.getElementsByTagName('a');
for(var i = links.length - 1; i >= 0; i--) {
if(links[i] && links[i].href) {
links[i].href = links[i].href.replace(/http:\/\/www\.google\.com\/page=(\d+)&view=(\d+)/,
'http://www.google.com/document/page=$1/field&view=$2&DONE');
}
}
Demo

Iframe onload seems to not work in time

after dynamicly creating some iframes, setting src and onload, I expect that the contents would be available for putting it to an array and sort the array. Next would be removing the iframes (interesting content already put in array) and create a table on my HTML-page. When no alert is set before sorting, the array is empty as the onload fires just before finishing the script. When an alert is place before sorting,I found the onload-procedure fired, array was populated and everything works fine?!! But I don't want to put an alert, can anyone explain what I did wrong? It's my first script so please help me to understand.
function LoadFile( ) {
var FName, PName, myID, myFrame;
var myBody = document.getElementById("StartList");
for ( var i = 0; i < FileList.length; i++ ) {
// Read input file into frame
FName = FileList[i].FName;
PName = FName + ".html";
myID = "iframe" + i;
// Create frame.
myFrame = document.createElement("iframe");
myFrame.setAttribute("id", myID);
myFrame.setAttribute("width","0");
myFrame.setAttribute("height","0");
myFrame.setAttribute('src', PName);
//Attach onload-event to frame, triggering ReadTableInfo.
if (myFrame.attachEvent){
myFrame.attachEvent("onload", function(){
ReadTableInfo();
});
} else {
myFrame.onload = function(){
ReadTableInfo();
};
}
myBody.appendChild(myFrame);
}
}
function ReadTableInfo() {
var a = document.getElementsByTagName("iframe")[idx];
var p = FileList[idx].FName;
var b = (a.contentWindow || a.contentDocument);
var td;
if ( b.document) {
b = b.document;
// Get and process table with functions and procedures.
var myTable = b.getElementsByTagName("Table")[5];
var myList = myTable.getElementsByTagName("TR");
var Name = "";
var Desc = "";
for ( var j = 0; j < myList.length; j++) {
Name = myTable.getElementsByTagName("TR") [j].getElementsByTagName("A")[0].innerHTML;
if ( myTable.getElementsByTagName("TR")[j].getElementsByTagName("TD")[1] != null) {
td = myTable.getElementsByTagName("TR")[j].getElementsByTagName("TD")[1];
Desc = td.textContent || td.innerText || "";
}
if ( searchval == "" || ( TestVal.test(Name) && searchkey == 1 ) || ( TestVal.test(Desc) && searchkey == 2 ) ) {
ProcList[ProcList.length++] = new AddProcList(Name.toLowerCase(), p.toLowerCase(), Desc);
}
Name = "";
Desc = "";
}
idx++;
}
}
function UpdateList( opt ) {
searchval = document.getElementById("edtSearchVal").value;
TestVal = new RegExp(".", "i");
if ( searchval !== "" ) {
if ( opt == 2 ) {
TestVal = new RegExp(searchval, "i"); // searchpattern for RegExp descriptions
} else {
TestVal = new RegExp(searchval.replace(" ","_"), "i"); // searchpattern for RegExp.
}
}
switch ( opt ) {
case 1: searchkey = 1;
break;
case 2: searchkey = 2;
break;
default:
searchkey = 3;
}
Init();
// Get package names from index.
SetFileList(); // Determines which external files to examine.
LoadFile(); // Loads the external files into iframes to be used later.
alert("Start generating list, this may take a while."); // Necessary to read frames! Don't know why???
var sortkeys = {FName:"a",PName:"a"}; // Sorting order of ProcList, which will be the listorder.
ProcList.keySort(sortkeys); // Sort ProcList.
TableCreate(); // Make new table with all entries in ProcList
}
Thanks for any comments, just here to learn from others :))
your LoadFile(); is loading content to iframe , and alert() is giving just enough time for iframe content to load completely, hence rest of the code works. If you remove alert then rest of the code is executed immediately before iframe content is loaded.
I would suggest to put onload even inside iframe page as well. Then propagate this event to parent window. To access parent container window you can do window.parent inside iframe.

Jquery Ajax image load works only in FF. Suspect "race condition."

I made a web app that loads images using jquery, ajax and json. I got it to work in Firefox, but alas, Safari and Chrome remain stubborn.
It has to do with a "race condition" where images don't load quickly enough, so I have a load event as well as a trigger event to wait until all images are loaded before appending the html to a container div.
Here is the link to the page that works in FF:
http://chereecheree.com/dagworthy/style.html
And some code:
var aSectionImages = new Array;
//count how many images are in a section:
var aImagesCount = new Array();
//count how many images of a particular section have been loaded
var aImagesLoaded = new Array();
var htmlString;
var jsonStyleImages = "images.json"
var jsonNavImages = "imagesNav.json";
//container div:
var scrollableArea = $("#scrollableArea");
$.getJSON(jsonNavImages, getNavIcons);
$.getJSON(jsonStyleImages, makeScroller);
//trigger this function on load event:
function imageLoaded(oImg){
//get the name of the section of images:
var locSectionId = (imageInSection(oImg.src)).replace(/\s|'/g, "_");
//get the file name of the current image
var locFileName = getFileName(oImg.src);
if (aImagesLoaded[locSectionId]===undefined){
aImagesLoaded[locSectionId] = new Array;
};
//check if it has already been loaded by seeing if it exists in the array of loaded images:
var inArray = false;
inArray = $.inArray(locFileName, aImagesLoaded[locSectionId]);
if (inArray == -1) {
//array.push returns the new length of the array:
var tempLength = aImagesLoaded[locSectionId].push(locFileName);
}
if (tempLength==aImagesCount[locSectionId]){
htmlString += "</div>";
scrollableArea.append(htmlString);
//after the html has been appended, force it to be 1000 px -- totally unstable hack.
scrollableArea.width(1000);
}
}
//helper function to get section name of a loading image:
function imageInSection(src){
var resultId=false;
var locFileName = getFileName(src);
for (var k = 0; k < aSectionImages.length; k++){
for(var j=0; j < aSectionImages[k].images.length; j++){
tempSrc = aSectionImages[k].images[j].src.split("/");
tempFileName = tempSrc[tempSrc.length-1];
if (tempFileName == locFileName) {
resultId = aSectionImages[k].id;
}
}
}
return resultId;
}
//helper function to get the file name of a loading image:
function getFileName(href){
var resultFileName=false;
var locSrc = href.split("/");
resultFileName = (locSrc[locSrc.length-1]);
return resultFileName;
}
//function called when ajax request is successful -- it puts together the html string that will be appended to the containter div
function makeScroller(data){
aSectionImages = data;
for (ii=0; ii<aSectionImages.length; ii++){
var locData = aSectionImages[ii];
var locId = locData.id.replace(/\s|'/g, "_");
aImagesCount[locId] = locData.images.length;
htmlString = "<div id=\"" + locId + "\">";
for (jj=0; jj<locData.images.length; jj++){
var oImage = new Image();
var locImage = locData.images[jj];
$(oImage)
.load(function(){
imageLoaded(oImage);
})
.attr("src", locData.images[jj].src);
if (oImage.complete && oImage.naturalWidth !== 0){
$(oImage).trigger("load");
}
//alert (oImage.width);
locImage.id ? locImage.id = " id=\""+locImage.id+"\" " : locImage.id = "";
htmlString += "<img height=\"" + locImage.height + "\"" + " width=\"" + oImage.width + "\"" + locImage.id + " src=\"" + locImage.src + "\" />";
}
}
}
But it's probably best to look at it online, as there is a plugin that's used.
Anyhow, the computed style for the container div shows up at "0px" sometimes, which is why I'm forcing it to "1000px" but that hack is not very stable.
Any ideas would be greatly appreciated.
Thanks!
--Daniel.
In this section:
$(oImage)
.load(function(){
imageLoaded(oImage);
})
.attr("src", locData.images[jj].src);
if (oImage.complete && oImage.naturalWidth !== 0){
$(oImage).trigger("load");
}
image.naturalWidth isn't available in all browsers (so undefined !== 0 won't be a correct check), but you don't need it to use it, just rearrange the code, like this:
$(oImage).one('load', function(){ imageLoaded(this); })
.attr("src", locData.images[jj].src)
.each(function() {
if (this.complete) $(this).trigger("load");
});
This uses .each() to loop through after setting the src and triggers the load event in case it came from cache (this.complete being instantly true indicates this). The .one() call ensures the load event only fires once, whether from cache or a normal load.

Categories