Alex
Alex

Reputation: 31

How can my Greasemonkey script find links with a specific pattern?

My target page has some links like:

http://example.com/ref.php?564646 

where the number varies.

How can I find these links and show them at the top of the page using a Greasemonkey script?

Upvotes: 2

Views: 2477

Answers (1)

Brock Adams
Brock Adams

Reputation: 93473

To search on arbitrary patterns of link hrefs, use the awesome power of jQuery and Regular Expressions (RegEx).

Then use jQuery to add the cloned links and use GM_addStyle() to position and style everything.

Here is a complete script that shows the process. You can also see the code in action at jsFiddle. :

// ==UserScript==
// @name     Use jQuery and RegEx to match arbitrary links
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

//--- Add a custom, regex-aware href selector
jQuery.extend (
    jQuery.expr[':'].hrefMatch = function (elem, J, Mtch, candidateNodeArry) {
        if (elem.hasAttribute ("href") ) {
            var zRegExp = new RegExp (Mtch[3], 'i');

            return zRegExp.test (elem.href);
        }

        return false;
    }
);

//-- Find links that match "ref.php?{some integer}"
matchedLinks = $("a:hrefMatch('ref\\.php\\?\\d+(?!\\w)')");

//-- Now add the links to the top of the page.
$("body").append ('<div id="gmMatchedLinks"></div>');
matchedLinks.clone (true, false). appendTo ("#gmMatchedLinks");

//-- Position the new links and style to taste.
GM_addStyle ( "                                 \
    #gmMatchedLinks a {                         \
        margin-right: 2em;                      \
    }                                           \
    #gmMatchedLinks {                           \
        position:   fixed;                      \
        top:        0px;                        \
        left:       0px;                        \
        background: orange;                     \
        padding:    1em;                        \
        z-index:    555;                        \
    }                                           \
" );

Upvotes: 2

Related Questions