2020-07-02

Tampermonkey script to show anchor tag links on dev.to articles

tampermonkey, javascript, productivity

banner

Image by Stefan Keller from Pixabay

Introduction

I started using Tampermonkey browser extension for some forums without "filtering" capabilities using a personal JavaScript code.

As I've been moderating dev.to, I found it necessary to go thru all links to verify they follow dev.to Content Policy.

Tampermonkey made it easy to display all anchor links on a specific domain using a client-side JavaScript YOU write.

I won't go into much details on Tampermonkey installation but will cover just how to create a script to display all anchor links in a post.

If you want to quickly just paste a CSS to achieve a similar effect, check out this CSS by Robin @darksmile92 Kretzschmar :)

1#article-body a::after {2  content: " (" attr(href) ") ";3  color: #52d849;4}

Result

What you will see in the end on every dev.to post looks like this.

Reference: Mesure your create react app build.

result

Tampermonkey script

Let's take a full source first (as it's short)

1// ==UserScript==2// @name         dev.to3// @namespace    http://tampermonkey.net/4// @version      0.15// @description  try to take over the world!6// @author       You7// @match        https://dev.to/*8// @grant        none9// ==/UserScript==10
11(function () {12  "use strict";13
14  // Your code here...15  document16    .querySelectorAll("#article-body a")17    .forEach(a =>18      a.insertAdjacentHTML("beforeEnd", `➡<strong style="color: red">${a.href}</strong>`),19    );20})();

@match is the important bit, where we instruct Tampermonkey which domain we want to execute the JavaScript code.

Note: Refer to Tampermonkey documentation for other UserScript header (such as @name).

Let's see how JavaScript code is implemented.

Selecting article links only

Each DEV article has an element with id='article-body', which is what we are interested in.

document.querySelectorAll("#article-body a");

As there are multiple links, I used querySelectorAll to match only anchor tags under #article-body using the descendant combinator.

Showing raw link next to anchor tags

As document.querySelectorAll("#article-body a") returns multiple anchor elements, we can iterate it with NodeList#forEach (Note that querySelectorAll returns a NodeList, not an array).

We can then get a hold of an anchor element in the callback (I labeld it as a), to which we can insert a custom HTML.

The custom HTML will be an aweful-looking red-colored strong element.

1.forEach(a =>2      a.insertAdjacentHTML(3        "beforeEnd",4        `➡<strong style="color: red">${a.href}</strong>`5      )6    )

Element.insertAdjacentHTML() provides a way to add a custom HTML next to the current element.

You can play around with position (first parameter, beforeEnd) the way you see fit.


Image by Stefan Keller from Pixabay