Skip to content

Instantly share code, notes, and snippets.

@yusukezzz
Last active February 19, 2018 08:04
Show Gist options
  • Save yusukezzz/14adbc7083e6a424054ea6abc2a41674 to your computer and use it in GitHub Desktop.
Save yusukezzz/14adbc7083e6a424054ea6abc2a41674 to your computer and use it in GitHub Desktop.
{
"content_scripts": [ {
"js": [ "newtab.js" ],
"matches": [ "*://*/*" ]
} ],
"description": "Always open external links in a new tab.",
"manifest_version": 2,
"name": "Open External Links in New Tab",
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "1.0"
}
function isExternalLink(anchor, host) {
var isHrefInternal = anchor.href.indexOf(host) != -1;
if (isHrefInternal) {
return false;
}
if (anchor.target != "" && anchor.target != "#") {
return false;
}
return true;
}
(function() {
var host = location.hostname;
document.addEventListener("click", function(event) {
var elem = event.target || event.srcElement;
while (elem) {
if (!(elem instanceof HTMLAnchorElement)) {
elem = elem.parentNode;
continue;
}
if (isExternalLink(elem, host)) {
// https://blog.jxck.io/entries/2016-06-12/noopener.html
elem.setAttribute("target", "_blank");
elem.setAttribute("rel", "noopener noreferrer");
}
break;
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment