gpt4 book ai didi

javascript - 我的 Greasemonkey 脚本没有找到页面上的元素(链接)?

转载 作者:行者123 更新时间:2023-12-03 00:18:34 27 4
gpt4 key购买 nike

网站是:lexin.nada.kth.se/lexin/#searchinfo=both,swe_gre,hej;

我的脚本是:

function main(){
var links=document.getElementsByTagName("a");
alert("There are " + links.length + "links.");
}

main();

运行脚本会给出两条警告消息,内容为

There are 0 links.

有什么想法为什么我无法从文档中获取适量的链接吗?为什么我会收到两次警报?

最佳答案

  1. 该警报会多次触发,因为该页面包含 iFrame(事实上,其 URL 与主页相同)。 Greasemonkey 将 iFrame 视为独立网页。使用@noframes来阻止它。

  2. 脚本找不到链接,因为它们是在页面加载和 GM 脚本触发后很长时间内通过 javascript 添加的。这是脚本和 AJAX 的常见问题。一个简单、强大的解决方案是使用 waitForKeyElements() (和 jQuery)。

这里是完整的示例脚本,它避免了 iFrame 并展示了如何获取动态链接:

// ==UserScript==
// @name _Find elements added by AJAX
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @match http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @noframes
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var totalUsrLinks = 0;

waitForKeyElements ("a[href*='/users/']", listLinks);

function listLinks (jNode) {
var usrMtch = jNode.attr ("href").match (/^.*\/users\/(\d+)\/.*$/);
if (usrMtch && usrMtch.length > 1) {
totalUsrLinks++;
var usrId = usrMtch[1];
console.log ("Found link for user: ", usrId, "Total links = ", totalUsrLinks);
}
}

关于javascript - 我的 Greasemonkey 脚本没有找到页面上的元素(链接)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729568/

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