Greasemonkey - 如何在以特定字符串开头的页面上找到并打开a URL?

时间:2015-03-10 16:01:33

标签: javascript greasemonkey

更新

我想为网址上以链接开头的每个链接打开一个新窗口。例如:

https://stackoverflow.com/users/3763853/tonakis2108

我希望它打开包含以下内容的页面上的每个链接:

https://stackoverflow.com/users

在新窗口或标签页上。 <{3}}“string”之后的网址在刷新后发生变化,我需要抓住它。

我尝试window.open("")https://stackoverflow.com/users*内输入但没有效果。

1 个答案:

答案 0 :(得分:0)

此操作在Google主页上运行,并打开包含mail.google.com的所有链接。

// ==UserScript==
// @name           Open Some Links
// @require        http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @namespace      http://www.yourDomainName.com/GreaseMonkey/
// @description    Opens the links to [something] when the page loads.
// @include        http*://www.google.com/
// @grant          none
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true); //make a safe instance of jQuery

var baseUrl = "mail.google.com";

//The $ function is an alias to the jQuery function. It's shorter, and most commonly used. 
//You pass a selector string into the $ function to select some elements on the page.
//We want to find all "a" tags (anchors) whose href attribute contains the baseUrl. *= is the "atribute contains" selector. 
//See: http://api.jquery.com/category/selectors/ for other selectors.
//To make it clearer, after adding in the baseUrl, this will be $( "a[href*='mail.google.com']" )
var matchingLinks = $( "a[href*='" + baseUrl + "']" );

//Use jQuery to loop over each link and run a function for each one.
//$(this) returns a jQuery wrapper for the current node.
//This is nice because we can use jQuery functions on it, like attr, which returns the value of the specified attribute.
//If the page contains more than one link to the same href, it will be opened multiple times.
$(matchingLinks).each( 
    function(index)
    {
        window.open( $(this).attr( "href" ) );
    }
);