What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my lack of JavaScript knowledge.

Here's the Greasemonkey script that's supposed to 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'm trying to implement it:

public void onPageFinished (WebView view, String url) {
                System.out.println("webview loaded");
                webView.loadUrl("javascript:/*...........Javascript code here........*/");

           }

Any suggestions on how to retrieve that link and load the page in the webview successfully? EDIT: There's another version of the script that achieves the same result.

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; 

Answer №1

Here is a simple Xpath query that can be converted into a CSS selector for better optimization.

Instead of using

window.location.href.match(/\?(.*)$/)[1]
, consider using
var query = window.location.href.match(/\?(.*)$/)[1];
if the initial version does not work properly.

Alternatively, you can use

var query = window.location.search.replace(/^\?/,'')
for a more concise solution.

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

Updated Android code:

var candidates = document.querySelector("div.dl_startlink > div");
if( !candidates.length) 
    return;
//The DIV with the highest zIndex contains the actual link; the others are irrelevant.
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; 

Condensed code for Android:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When implementing Firebase Cloud Messaging with React, the token generated by firebase.messaging().getToken() will vary with every refresh

I'm working on a React web app using Gatsby and I want to integrate push notifications through FCM. My firebase-messaging-sw.js service worker is set up, and I'm trying to retrieve a token using the following method in my app: messaging .req ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

What is the best way to use AJAX to update multiple items with a common customer number on a SharePoint list?

Currently, I am facing an issue while attempting to update a SharePoint list using JavaScript/ajax. The script is running smoothly until it reaches the ajax function, where it encounters a failure. Specifically, it mentions that the ItemID is not defined, ...

Utilizing jQuery's .done() and .fail() methods to handle

Our goal here is to control the outcome of the createSite function. If it returns {ac:failed}, then the .fail(failOption) will be triggered; otherwise, the sendMail or .done(sendMail) function will be executed while still retaining the data from the crea ...

Server headers in Node.js

As a newcomer to web development, I am currently delving into the world of node.js to create an app that involves retrieving data via REST and implementing search and sort functionalities. However, I've hit a roadblock when it comes to understanding h ...

Preventing Multiple Form Submissions in JavaScript

I'm having an issue with my form submission to Parse where, after adding client-side validation, the data is being double submitted to the database. Despite adjusting my code based on other Stack posts and being new to JavaScript, I'm still expe ...

Guide on populating an AutoCompleteTextView with contact names on Android version 2.1

Currently, I am working on an AutoCompleteTextView and my goal is to have it autocomplete contact names as the user inputs. However, I have encountered a challenge as the Contacts.People method has been deprecated. The new documentation suggests using Cont ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

Utilizing AJAX to send an array of data in JSON format

I have successfully extracted specific elements from a form, stored them in an array and now want to convert this array into a JSON object to send it to a PHP file via AJAX. However, I am facing some issues with my code. Here's what I have done so far ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

Specify touch event regions with the ngTouch directive

I recently implemented ngTouch in my AngularJs web app to detect swipe left and right gestures. I am using this feature to open and close a side bar menu. Currently, the swipe events are linked to the entire wrapper like this <div ng-style="body_st ...

Step-by-step guide: Assigning a color to a card element in MaterializeCSS

I am currently working on a project using Vue.js where I want to display colored cards from MaterializeCSS. The colors are stored as hex codes in a separate database and are part of items looped through with the v-for loop, like this: <div ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

Google Maps autocomplete feature is causing the input to update only after clicking in ng-model

After fetching a Google Maps place ID from a REST API, I utilize the Google Maps API to retrieve the place object in this manner: var geocoder = new google.maps.Geocoder; geocoder.geocode({ 'placeId': data.city }, fun ...

Is the three.js.master folder necessary for utilizing OBJLoader2.js? I keep getting a 404 error when trying to access it

As I venture into using three.js, I am attempting to import an OBJ file using OBJLoader2.js locally (without npm). However, I am encountering a 404 error for three.module.js, MeshReceiver.js, and OBJLoaderParser when trying to add import {OBJLoader2} from ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

How can you display a border around a <td> element in an HTML table only when it contains data, using jQuery or JavaScript?

My HTML table consists of the following structure: <table class="table table-bordered"> <thead> <tr> <th>Tag</th> <th>Time Code</th> </tr> </thea ...

Is there a way to swap out a div with another using ajax and php?

i am looking to update the content from readmore.php into <div id='box'> based on id_pages in index.php after clicking <a class=readmore> Read More </a>. i have been trying to figure out how to retrieve data from readmore.p ...