Add rel ="noreferrer noopener" to external links by default as a privacy & security measure

Adding noopener tag to rel attribute is a must as a security measure.

noreferrer is somewhere in-between as a privacy measure. By default, the application can query the user agent’s DNT header and if DNT is checked it can add noreferrer tag to every external link on the page. And ideally it should be implemented in the backend if possible since some privacy-aware users disable JavaScript by default by using browser extensions such as NoScript.

Currently, I am using the following hack for my own blog. But like I said, not all users might be using JS.

// Make links in the articles open in a new tab & add "noreferrer noopener"
var post_links = document.querySelectorAll("article a");
for (let i = 0, tags = ["noreferrer", "noopener"]; i < post_links.length; i++) {
    if (post_links[i].href.startsWith("/")) {
        continue;
    }

    post_links[i].target = "_blank";

    for (const tag of tags) {
        if (!post_links[i].rel.includes(tag)) {
            post_links[i].rel += " " + tag;
        }
    }
}

Thanks for this code, which I like very much and have added to my write.as blogs as a security measure.

Recently I had a need to add links in a blog page to other internal parts of the same page. I was confused as to why they were being opened in a new browser page rather than navigating to the specified header staying within the page. Before I realized what caused that issue, I posted a forum message about it here.

Today I remembered I had added this js code to my configuration, which included this line of code which opens all links in a new tab:

post_links[i].target = "_blank";

So I modified the code to execute that line ONLY for links external to write.as/writeas.com. Now links to internal parts of a blog page work stay within the same page, while still having protection when navigating to external sites (which continue to open in a new page with the ‘noreferrer noopener’ security measure).

h = post_links[i].href;
if (!h.includes("write.as") && !h.includes("writeas.com") {
  post_links[i].target = "_blank";
}

Again, thanks for your code which is a prudent security measure.

1 Like