3

I want to write a user script for my browsers (Opera, Chromium) that removes links containing predefined keywords. For example, a link <a href="foo">bar</a> should simply vanish from the page when foo is part of the blacklist.

How do i remove duplicate links from a page except first shows how to get and filter a site, but I want to do this directly via a user script. Any ideas how I would apply the filter on every page load?

Community
  • 1
  • 1
htorque
  • 1,818
  • 4
  • 19
  • 22

3 Answers3

5

Get the document.links collection. If any of their .href properties match your blacklist, set their style.display property to 'none'.

e.g.

function removeLinks () {
  var blackList = /foo|bar|baz/;
  var link, links = document.links;
  var i = links.length;

  while (i--) {
    link = links[i];
    if (blackList.test(link.href)) {
      link.style.display = 'none';
    }
  }
}

Edit

To remove duplicate links is a similar exercise. First convert the links HTMLCollection to a plain array, then as you iterate over them use their hrefs as create properties of an object. If the href is already a property, hide it using the above method or link.parentNode.removeChild(link).

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Would it be possible to remove all links on the page (instead of just the links in the blacklist)? – Anderson Green Feb 19 '13 at 03:19
  • Sure, just remove the `if` test. If you want to remove the link node from the DOM, use `link.parentNode.removeChild(link);` – RobG Feb 19 '13 at 04:41
0

You could use XPATH and its contains() function to match the links via document.evaluate.

Dive Into Greasemonkey has an exampl eof selecting and iterating over nodes using XPATH.

for (var i = 0; i < blacklist.length; i++) {
  var links = document.evaluate('//a[contains(@href, "' + blacklist[i] + '"]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  for (var j = 0; j < links .snapshotLength; j++) {
    var link = links.snapshotItem(j);
    link.parentNode.removeChild(link);
  }
}
Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
-1

You could use something like this

$("a[href*='" + foov + "']").css('display', 'none')
Digbyswift
  • 10,310
  • 4
  • 38
  • 66