remove_redirect

remove redirects in zhihu.com

当前为 2024-12-20 提交的版本,查看 最新版本

// ==UserScript==
// @name         remove_redirect
// @namespace    https://github.com/mikelxk/remove_redirect
// @version      0.0.2
// @author       mikelxk
// @description  remove redirects in zhihu.com
// @license      MIT
// @icon         https://vitejs.dev/logo.svg
// @match        *://*.zhihu.com/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  function updateLinkHref(link) {
    if (
      link.href.includes("https://link.zhihu.com/?target=") ||
      link.href.includes("http://link.zhihu.com/?target=")
    ) {
      const urlParams = new URLSearchParams(link.href.split("?")[1]);
      const newLink = urlParams.get("target");
      if (newLink) {
        link.href = decodeURIComponent(newLink);
        return link.href;
      }
    }
    return null;
  }
  function updateAllLinks() {
    const links = document.querySelectorAll("a");
    links.forEach((link) => updateLinkHref(link));
  }
  updateAllLinks();
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === "childList") {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            const element = node;
            if (element.tagName === "A") {
              updateLinkHref(element);
            } else {
              const links = element.querySelectorAll("a");
              links.forEach((link) => updateLinkHref(link));
            }
          }
        });
      }
    });
  });
  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });
  document.addEventListener("click", (event) => {
    const target = event.target;
    if (target.tagName === "A") {
      const newHref = updateLinkHref(target);
      if (newHref) {
        event.preventDefault();
        window.location.href = newHref;
      }
    }
  });
})();