Here's another userscript, which wraps any element with an onclick="document.location='some_url'"
attribute in an <a href=some_url>
element and removes the onclick
.
I wrote it for a specific site, but it's generic enough that it may be useful to others. Don't forget to change the @match URL below.
This works when the links are loaded by an AJAX call, hence the MutationObserver.
// ==UserScript==
// @name JavaScript link fixer
// @version 0.1
// @description Change JavaScript links to open in new tab/window
// @author EM0
// @match http://WHATEVER-WEBSITE-YOU-WANT/*
// @grant none
// ==/UserScript==
var modifyLink = function(linkNode) {
// Re-create the regex every time, otherwise its lastIndex needs to be reset
var linkRegex = /document\.location\s*=\s*\'([^']+)\'/g;
var onclickText = linkNode.getAttribute('onclick');
if (!onclickText)
return;
var match = linkRegex.exec(onclickText);
if (!match) {
console.log('Failed to find URL in onclick text ' + onclickText);
return;
}
var targetUrl = match[1];
console.log('Modifying link with target URL ' + targetUrl);
// Clear onclick, so it doesn't match the selector, before modifying the DOM
linkNode.removeAttribute('onclick');
// Wrap the original element in a new <a href='target_url' /> element
var newLink = document.createElement('a');
newLink.href = targetUrl;
var parent = linkNode.parentNode;
newLink.appendChild(linkNode);
parent.appendChild(newLink);
};
var modifyLinks = function() {
var onclickNodes = document.querySelectorAll('*[onclick]');
[].forEach.call(onclickNodes, modifyLink);
};
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function(obj, callback) {
if (MutationObserver) {
var obs = new MutationObserver(function(mutations, observer) {
if (mutations[0].addedNodes.length || mutations[0].removedNodes.length)
callback();
});
obs.observe(obj, { childList:true, subtree:true });
}
};
})();
(function() {
'use strict';
observeDOM(document.body, modifyLinks);
})();
Yeah I always thought this is extremely silly – Gigala – 2014-07-28T10:20:09.413
see also: https://superuser.com/questions/854797/why-does-ctrl-click-not-open-some-links-in-a-new-tab
– braham-snyder – 2019-06-07T13:57:51.283Yes, href is set to # and JS is invoked on onclick event of links (site doesn't work with JS disabled). Perhaps there's some sort of browser plugin that can deal with this. – Karan – 2013-06-07T01:36:37.063
4
There is a request for a solution in Mozilla's Bugzilla: Bug 55696 - "Force JavaScript link to open in new window or new tab".
– pabouk – 2013-08-05T13:52:10.810