Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - My Greasemonkey script is not finding the elements (links) on the page?

The website is: lexin.nada.kth.se/lexin/#searchinfo=both,swe_gre,hej;

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. The alert fires more than once because that page contains iFrames (with, de facto, the same URL as the main page). Greasemonkey treats iFrames as if they were standalone web pages. Use @noframes to stop that.

  2. 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).

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...