2

I'm trying to add attributes for external links such as the rel="noopener noreferrer" for all the external links where target="_blank". I've tried using modules such as the noreferrer and sel, but neither affect the links in my views.

How can I add rel="noopener noreferrer" to all links globally where target="_blank"?

3
  • 1
    As for affecting links in Views, it depends on how the links are configured in Views. Are these links from a URL field being displayed? Or links from a page display being shown embedded in Views? Or links in custom text in the header/footer? Commented Feb 10, 2021 at 2:28
  • 1
    Also, the most popular module for this is Extlink. Commented Feb 10, 2021 at 2:28
  • Globally like also all links inside body text fields?
    – leymannx
    Commented Feb 10, 2021 at 12:53

1 Answer 1

2

By implementing hook_link_alter in either a custom module or your theme.

The code (untested) would be similar to:

/**
 * Implements hook_link_alter().
 */
function MODULE/THEME_link_alter(&$variables) {
  if (isset($variables['options']['attributes']['target']) && $variables['options']['attributes']['target'] == '_blank') {
    $variables['options']['attributes']['rel'] = 'noopener noreferrer';
  }
}
1
  • This would add to the attribute even if already set to noopener noreferrer. The Noopener Filter module does it like above, but adds if (empty($variables['options']['attributes']['rel']) || !in_array('noopener', $variables['options']['attributes']['rel'], TRUE)) {. It also has it as an array, not a string. Like $variables['options']['attributes']['rel'][] = 'noopener';
    – mbomb007
    Commented Aug 31, 2023 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.