Add noopener to Link Tags II

Using a plugin to add noopener noreferer to link tags.


MODX Forum user, apathy, asked for a way to automatically add rel="noopener" to link code in MODX. In the previous article, we discussed the security vulnerability caused by using target="_blank" by itself in link code, and the solution for it. In this article, we'll see a way to fix the links automatically with a plugin.

MODX logo

The Plugin

The best solution, as we discussed in the previous article, is to add this code to the link tags: rel="noopener noreferrer". Here's a plugin attached to the OnWebPagePrerender System Event that will insert that code automatically into your web page.


/* Don't act on pages that are already correct */
if (strpos($modx->resource->_output, 'noopener') !== false) {
    return;
}

/* Add the fix after the _blank attribute */
if (strpos($modx->resource->_output, '_blank') !== false) {
    $modx->resource->_output = str_replace('target="_blank"',
        'target="_blank" rel="noopener noreferrer" ',
        $modx->resource_output);
}

return;

If you create a plugin (let's call it FixLinks) with the code above and attach it to the OnWebPagePrerender System Event, it will automatically correct any target="_blank" links.


Drawbacks

Although this is by far the easiest fix for the problem, it has several shortcomings. First, it assumes that if one link on the page has been fixed, they all have. Second, it assumes that the target="_blank" code takes exactly that form. It will fail, for example, if the user has used single quotes or if the code has a space before or after the equals sign. Finally, it will slow down page loads for every page in the front end of your site.

There are several ways to fix the first two problems, but the last one is insurmountable. Worse yet, fixing the first two problems would slow down page loads even further. In the following articles, we'll look at methods that actually rewrite the link code and save it to the database. That only needs to happen once, and once it's done, page-load times will not be affected at all.


Coming Up

In the following article, we'll see how to fix this problem with a snippet that modifies the code and saves it to the database. We'll also see a fix for the problem with Articles.




Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at Hosting.com (formerly A2 Hosting). (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)