Open links in new tab

Open links in new tab (Ctrl-click or Middle-click loads it in background), works on dynamically added content too.

As of 2016-03-11. See the latest version.

// ==UserScript==
// @name         Open links in new tab
// @description  Open links in new tab (Ctrl-click or Middle-click loads it in background), works on dynamically added content too.
// @include      *
// @namespace    wOxxOm.scripts
// @author       wOxxOm
// @version      1.0.2
// @license      MIT License
// @grant        GM_openInTab
// @run-at       document-start
// @require      https://greasyfork.org/scripts/12228/code/setMutationHandler.js
// ==/UserScript==

attachHandler([].slice.call(document.getElementsByTagName('a')));

setMutationHandler(document, 'a', function(nodes) {
	attachHandler(nodes);
	return true;
});

function attachHandler(nodes) {
	nodes.forEach(function(node) {
		if (node.target != '_blank') {
			node.onclick = clickHandler;
			node.addEventListener('click', clickHandler);
		}
	});
}

function clickHandler(e) {
	if (e.button > 1)
		return;
	e.preventDefault();
	e.stopPropagation();
	e.stopImmediatePropagation();
	GM_openInTab(this.href, e.button || e.ctrlKey);
}