Skip to content

Instantly share code, notes, and snippets.

@jasondmoss
Last active November 22, 2019 03:35
Show Gist options
  • Save jasondmoss/7345498 to your computer and use it in GitHub Desktop.
Save jasondmoss/7345498 to your computer and use it in GitHub Desktop.
Open external, or specified, links in new tab/window.
/**
* Securely open a new window from given anchor element.
*
* @param {NodeElement} anchor
*
* @method newWindowAnchor
*
* jshint esversion: 6
*/
function newWindowAnchor(anchor)
{
"use strict";
anchor.setAttribute("rel", "noopener noreferrer");
anchor.addEventListener("click", event => {
event.preventDefault();
let targetUrl = anchor.getAttribute("href");
let newWindow = window.open(targetUrl, "_blank");
/**
* Sever the reference of the new tab/window from the parent.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/opener
*/
newWindow.opener = null;
});
}
/* <> */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment