Copy Magnet Links

Copy all unique magnet links on a webpage with a button(一键复制所有磁力链接)

// ==UserScript==
// @name         Copy Magnet Links
// @namespace    http://your.namespace.com
// @version      0.7
// @description  Copy all unique magnet links on a webpage with a button(一键复制所有磁力链接)
// @author       ChatGpt3.5
// @match        https://www.javbus.com/*
// @grant        none
// @license         GPL-3.0-only
// ==/UserScript==

(function() {
  'use strict';

  // 定义磁力链接的正则表达式
  const magnetRegex = /magnet:?\?xt=urn:btih:([0-9a-f]{40})/ig;

  // 添加复制按钮
  function addCopyButton() {
    const copyButton = document.createElement('button');
    copyButton.textContent = 'Copy All Magnet Links';
    copyButton.style.position = 'fixed';
    copyButton.style.top = '10px';
    copyButton.style.left = '10px';
    copyButton.style.zIndex = '9999';
    copyButton.addEventListener('click', copyAllMagnetLinks);

    // Append the button to the body
    document.body.appendChild(copyButton);
  }

  // 复制所有磁力链接
  function copyAllMagnetLinks() {
    const magnetLinksSet = new Set(); // Use a Set to ensure uniqueness
    // 遍历所有元素
    Array.from(document.querySelectorAll('*')).forEach(function(element) {
      // 匹配磁力链接
      const matches = element.textContent.match(magnetRegex);
      // 如果匹配成功,则加入Set
      if (matches) {
        matches.forEach(match => {
          const magnetLink = match;
          magnetLinksSet.add(magnetLink);
        });
      }
    });

    // 如果有磁力链接,则复制到剪贴板
    if (magnetLinksSet.size > 0) {
      const allLinks = Array.from(magnetLinksSet).join('\n');
      navigator.clipboard.writeText(allLinks);
      alert('All unique magnet links copied to clipboard!');
    } else {
      alert('No magnet links found on this page.');
    }
  }

  // Wait for the DOMContentLoaded event or use setTimeout to add the button
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addCopyButton);
  } else {
    addCopyButton();
  }
})();