Đây là một usercript khác, bao bọc bất kỳ phần tử nào với một onclick="document.location='some_url'"thuộc tính trong một <a href=some_url>phần tử và loại bỏ phần tử onclick.
Tôi đã viết nó cho một trang web cụ thể, nhưng nó đủ chung chung để nó có thể hữu ích cho những người khác. Đừng quên thay đổi URL @match bên dưới.
Điều này hoạt động khi các liên kết được tải bởi một cuộc gọi AJAX, do đó là MutingObserver.
// ==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);
})();