MCPcopy Index your code
hub / github.com/XIU2/UserScript / forceTarget

Function forceTarget

Autopage.user.js:2435–2486  ·  view source on GitHub ↗
(pageE)

Source from the content-addressed store, hash-verified

2433
2434 // 强制新标签页打开链接
2435 function forceTarget(pageE) {
2436 if (curSite.blank === 1) {
2437 document.head.appendChild(document.createElement('base')).target = '_blank';
2438
2439 } else if (curSite.blank === 5 || curSite.blank === 6) { // 清理 <a> 元素的点击事件
2440 if (!pageE) pageE = getAll(curSite.pager.pageE)
2441 pageE.forEach(function (dd) {
2442 getAllCSS('a[href]:not([target="_blank"]):not([href^="#"]):not([href^="javascript:"])',dd).forEach(function (a) {
2443 if (a.href.slice(0,4) == 'http') {
2444 const clonedLink = a.cloneNode(true); // 克隆原 a 元素
2445 clonedLink.target = '_blank'; // 通过添加 target="_blank" 属性来新标签页打开,可以解决大部分情况
2446 if (curSite.blank === 6) clonedLink.addEventListener('click', function(e) {e.stopPropagation();}); // 如果添加 target="_blank" 属性无效(依然在当前网页跳转打开),那么说明其父元素的事件委托中阻止了默认打开链接事件,因此对该 <a> 元素添加点击事件并阻止冒泡(避免父元素事件委托捕获该元素的点击事件)
2447 a.insertAdjacentElement('afterend', clonedLink); // 把克隆的元素插入原 a 元素后面
2448 a.remove(); // 删除原 a 元素
2449 }
2450 });
2451 });
2452 return pageE
2453
2454 } else if (curSite.blank === 4) {
2455 if (!pageE) pageE = getAll(curSite.pager.pageE)
2456 pageE.forEach(function (dd) {getAllCSS('a[href]:not([target="_blank"]):not([onclick]):not([href^="#"]):not([href^="javascript:"])',dd).forEach(function (a) {if (a.href.slice(0,4) == 'http') {a.target = '_blank';}});});
2457 return pageE
2458
2459 } else {
2460 let d;
2461 if (curSite.blank === 2) {
2462 d = document.body
2463 } else if (curSite.blank === 3) {
2464 let dd = toE5pop(getAll(curSite.pager.pageE));
2465 if (dd && dd.parentElement != null) d = dd.parentElement
2466 }
2467 if (!d) return
2468
2469 function forceTarget_(target, e){
2470 if (target.href && target.target != '_blank' && !(target.getAttribute('onclick')) && target.href.slice(0,4) == 'http' && target.getAttribute('href').slice(0,1) != '#') {
2471 e.stopPropagation(); // 阻止冒泡(避免被父元素事件委托捕获)
2472 e.preventDefault(); // 阻止默认打开链接事件
2473 GM_openInTab(target.href, {active: true,insert: true,setParent: true});
2474 }
2475 }
2476 d.addEventListener('click', function(e) {
2477 //console.log(e.target.tagName, e.path)
2478 if (e.target.tagName === 'A') {
2479 forceTarget_(e.target, e);
2480 } else {
2481 let path = e.path || e.composedPath();
2482 for (let i = 1; i < path.length - 4; i++) {if (path[i].tagName === 'A') {forceTarget_(path[i], e); break;}}
2483 }
2484 });
2485 }
2486 }
2487
2488 // 清理元素上绑定的事件(不包括父元素上监听的事件委托)
2489 // css 为元素选择器(也支持 Xpath)

Callers 1

processElemsFunction · 0.85

Calls 4

getAllFunction · 0.85
toE5popFunction · 0.85
forceTarget_Function · 0.85
getAllCSSFunction · 0.70

Tested by

no test coverage detected