我的Greasemonkey脚本没有找到页面上的元素(链接)? [英] My Greasemonkey script is not finding the elements (links) on the page?

查看:165
本文介绍了我的Greasemonkey脚本没有找到页面上的元素(链接)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的脚本是: p>

My script is:

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

main();

运行脚本给我两个警报消息说

Running the script gives me two alert messages saying


有0个链接。

There are 0 links.

任何想法为什么我可以不能从文档中获取正确的链接数量?为什么要两次获得警报?

Any ideas why I can't get the right amount of links from the document? And why do I get the alert twice?

推荐答案


  1. 警报不止一次因为该页面包含iFrames(与事实上,与主页相同的URL)。 Greasemonkey将iFrames视为独立网页。使用 @noframes 来阻止。

脚本没有找到链接,因为它们被添加,通过javascript加载页面,GM脚本启动后很久。这是脚本和AJAX的常见问题。一个简单而强大的解决方案是使用 waitForKeyElements()(和jQuery)。

The script is not finding the links because they are added, by javascript, long after the page loads and the GM script fires. This is a common problem with scripts and AJAX. A simple, robust solution is use waitForKeyElements() (and jQuery).

这是一个完整的示例脚本,可以避免iFrame,并显示如何获取动态链接:

Here is a complete sample script that avoids the iFrames and shows how to get dynamic links:

// ==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);
    }
}

这篇关于我的Greasemonkey脚本没有找到页面上的元素(链接)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆