替换 Bilibili 部分链接为带 href 的常规 a 元素

替换 Bilibili 部分链接为带 href 的常规 a 元素,使其右键菜单出现“在新标签页打开链接”“在新窗口打开链接”等选项

当前为 2023-07-09 提交的版本,查看 最新版本

// ==UserScript==
// @name         替换 Bilibili 部分链接为带 href 的常规 a 元素
// @namespace    myitian.bili.replaceToHrefA
// @version      0.2
// @description  替换 Bilibili 部分链接为带 href 的常规 a 元素,使其右键菜单出现“在新标签页打开链接”“在新窗口打开链接”等选项
// @author       Myitian
// @license      MIT
// @match        https://www.bilibili.com/*
// @icon         https://www.bilibili.com/favicon.ico
// @grant        none
// ==/UserScript==

function replace() {
  var es;
  var c = 0;
  es = document.querySelectorAll('a.jump-link[data-url]:not([data-rbltha-replaced])');
  for (let e of es) {
    replaceUrl(e);
    c++;
  }
  es = document.querySelectorAll('a.jump-link[data-user-id]:not([data-rbltha-replaced])');
  for (let e of es) {
    replaceUserId(e);
    c++;
  }
  es = document.querySelectorAll('.opus-text-rich-hl.at[data-rid]:not([data-rbltha-replaced])');
  for (let e of es) {
    replaceUserId(changeElementTagName(e, 'a'), 'data-rid');
    c++;
  }
  es = document.querySelectorAll('.root-reply-avatar[data-user-id]:not([data-rbltha-replaced]),.user-name[data-user-id]:not([data-rbltha-replaced]),.sub-user-name[data-user-id]:not([data-rbltha-replaced]),.sub-reply-avatar[data-user-id]:not([data-rbltha-replaced])');
  for (let e of es) {
    replaceUserId(changeElementTagName(e, 'a'));
    c++;
  }
  console.log('[RBLTHA] Replacement completed. ' + c + ' element(s) effected.');
}

function replaceUrl(e) {
  e.href = e.dataset.url;
  e.setAttribute("data-rbltha-replaced", "");
  e.target = '_blank';
  e.onclick = null;
  e.addEventListener('click', stopImmediatePropagation);
}

function replaceUserId(e, attr = 'data-user-id') {
  e.href = 'https://space.bilibili.com/' + e.getAttribute(attr);
  e.setAttribute("data-rbltha-replaced", "");
  e.target = '_blank';
  e.onclick = null;
  e.addEventListener('click', stopImmediatePropagation);
}

function changeElementTagName(element, newname) {
  var ne = document.createElement(newname);
  for (let t of element.attributes) {
    ne.setAttribute(t.name, t.value)
  }
  for (let t of element.childNodes) {
    ne.appendChild(t);
  }

  var p = element.parentElement;
  var nxt = element.nextSibling;
  p.removeChild(element);
  p.insertBefore(ne, nxt);
  return ne;
}

function stopImmediatePropagation() {
  event.stopImmediatePropagation();
}

replace();
window.addEventListener('mousedown', replace);
window.addEventListener('keydown', replace);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址