【问题标题】:Use Greasemonkey to replace links, to images, with images?使用 Greasemonkey 用图像替换链接、图像和图像?
【发布时间】:2013-05-17 11:37:20
【问题描述】:

我是 Greasemonkey 的新手,我想用 <img> 标签替换图片链接。

例如,this forums page 有一堆链接,例如:

<a target="_blank" href="http://url.com/pic.gif">http://url.com/pic.gif</a>

我想用以下图片替换这些链接:

<img src="http://url.com/pic.gif">


我在网上搜索并设法找到类似this Greasemonkey user's group的东西。
但是,我编辑的代码:

var i, x = document.evaluate (
    '//*[@target="_blank"][@href="="]',
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null
);
for (i = 0; i < x.snapshotLength; i++)
    x.snapshotItem(i).setAttribute("href", "img src");

似乎不起作用。

请告知我应该如何创建这个脚本。

【问题讨论】:

标签: javascript html firefox hyperlink greasemonkey


【解决方案1】:

替换图片链接并不难。但是,我建议您保留链接,但在其中显示图片。这样,如果出现问题,您可以单击。例如,that sample page you gave 的大部分链接图像都在一个死网站上。

其他链接图像仅看起来像它们指向图像或可能因“热链接”而被阻止。

为了使代码健壮和简单,我们使用jQuerywaitForKeyElements

这里是一个完整的工作脚本,它将that sample site上的有效负载图像链接:

// ==UserScript==
// @name    _Image delinker
// @include http://forums.hardwarezone.com.sg/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant   GM_addStyle
// ==/UserScript==

var imageExtensions = ["gif", "png", "jpg", "jpeg"];
var imgExtRegex     = new RegExp(
    '\\.(' + imageExtensions.join ('|') + ')$', 'i'
);

/*-- Tune the CSS path, for each site, to only find links that can be
    the image links you care about.
*/
//-- For forums.hardwarezone.com.sg
waitForKeyElements ("td.page div > a", delinkImage);

function delinkImage (jNode) {
    var imgUrl  = jNode.attr ("href");

    if (imgExtRegex.test (imgUrl) ) {
        //-- Found an image link.  Replace contents.
        jNode.html (
            '<img src="' + imgUrl
            + '" class="gmDeLinked" alt="GM replaced image">'
        );
    }
}

GM_addStyle ( "                                 \
    img.gmDeLinked {                            \
        border:             1px solid lime;     \
        max-width:          90vw;               \
    }                                           \
" );

【讨论】:

  • 感谢 Brock Adams,您的脚本很棒。我希望我能有时间探索greasemonkey更多有用的功能,也希望能学习如何编写自己的脚本:)
  • 不客气。查找 jQuery 并学习如何使用它修改网页;到时候你就可以写脚本了。
猜你喜欢
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
相关资源
最近更新 更多