gpt4 book ai didi

javascript - 如何将此 Greasemonkey 代码转换为适用于 Android 的 JavaScript?

转载 作者:行者123 更新时间:2023-11-29 02:06:53 25 4
gpt4 key购买 nike

我正在尝试加载一个页面,然后在其上运行 javascript 代码,我找到了一个 Greasemonkey 脚本,它做同样的事情,但我在 android 中实现同样的事情时遇到了问题,可能是因为我对它一无所知javascript.

这是 Greasemonkey 脚本;它应该提供一个新链接:

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


这就是我想要运行它的方式:

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

}

关于如何获取该链接并在 WebView 中加载该页面的任何想法?编辑:另一个版本做同样的事情。

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,这里只是简单的Xpath查询,可以重写为CSS选择器。

我还决定替换 window.location.href.match(/\?(.*)$/)[1]。如果我的版本不起作用,请将前两行替换为 var query = window.location.href.match(/\?(.*)$/)[1];

实际上,也许 var query = window.location.search.replace(/^\?/,'') 就足够了。

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

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;

精简版:

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

关于javascript - 如何将此 Greasemonkey 代码转换为适用于 Android 的 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9529534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com