Last active
November 22, 2019 03:35
-
-
Save jasondmoss/7345498 to your computer and use it in GitHub Desktop.
Open external, or specified, links in new tab/window.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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