首页  编辑  

油猴脚本:复制当前页面地址为URL和链接

Tags: /计算机文档/软件应用技巧/   Date Created:
Edge浏览器有个很好的功能,就是在地址栏复制URL的时候,能够自动把地址复制为URL文本和链接,当你在文本框中粘贴的时候,就自动粘贴URL地址,如果是在Word,HTML编辑器中粘贴的时候,就会自动粘贴为链接 <a href="url">页面标题</a>。

Chrome中没有类似的功能,我们可以用插件实现,或者用油猴脚本实现。
油猴脚本:
// ==UserScript==
// @name         Copy Url
// @namespace    http://tampermonkey.net/
// @version      1.0
// @license      GPL-3.0-only
// @description  Copy current page url as text & link
// @author       Kingron
// @match        *://*/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        GM_registerMenuCommand
// @grant        GM_openInTab
// ==/UserScript==

(function() {
    'use strict';
    var linkMenu;
    var linkMove;

    function copy(title, url, event) {
        const href = `<a href="${url}" title="${decodeURIComponent(url)}">${title.trim()}</a>`;

        try {
            const clipboardItem = new ClipboardItem({
                'text/plain': new Blob([url], { type: 'text/plain' }),
                'text/html': new Blob([href], { type: 'text/html' })
            });
            navigator.clipboard.write([clipboardItem]);
            console.log('复制成功:', title, href);
        } catch (err) {
            console.error("复制失败: ", err);
            const cd = event?.clipboardData || window.clipboardData;
            if (cd) {
                console.log('使用老方法复制: ', title, href);
                cd.setData('text/plain', url);
                cd.setData('text/html', href);
            }
        }
    }

    document.addEventListener('mousemove', function(event) {
        linkMove = event.target.closest('a');
    });

    document.addEventListener('copy', async function (event) {
        const selection = document.getSelection();
        if (selection && selection.toString().trim()) {
            return; // If selection then return
        }
        if (linkMove) {
            copy(linkMove.textContent, linkMove.href, event);
        } else {
            copy(document.title, window.location.href, event);
        }

        event.preventDefault();
    });

    GM_registerMenuCommand('复制超链接', function(e) {
        if (linkMenu) copy(linkMenu.textContent || linkMenu.innerText || linkMenu.href, linkMenu.href || window.getSelection().toString());
    });
    GM_registerMenuCommand('复制链接文字', function(e) {
        if (linkMenu) navigator.clipboard.writeText(linkMenu.textContent || linkMenu.innerText || window.getSelection().toString() || linkMenu.href);
    });
    GM_registerMenuCommand('复制解码后的链接地址', function(e) {
        if (linkMenu) navigator.clipboard.writeText(decodeURIComponent(linkMenu.href));
    });

    document.addEventListener('contextmenu', function(event) {
        linkMenu = event.target.closest('a');
    });
})();
Chrome插件:
manifest.json:
{
  "manifest_version": 3,
  "name": "Clipboard URL Formatter",
  "version": "1.0",
  "description": "Automatically format copied URL and set clipboard content.",
  "permissions": ["activeTab", "clipboardWrite", "contextMenus"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["http://*/*", "https://*/*"]
}

content.js:
var linkMove;
var linkMenu;

function copy(title, url) {
  title = title?.trim();
  const href = `<a href="${url}">${title}</a>`;

  const clipboardItem = new ClipboardItem({
    "text/plain": new Blob([url], { type: "text/plain" }),
    "text/html": new Blob([href], { type: "text/html" }),
  });
  try {
    navigator.clipboard.write([clipboardItem]);
    console.log("链接已复制: ", title, href);
  } catch (err) {
    console.error("复制链接失败: ", title, href, err);
  }
}

document.addEventListener("mousemove", function (event) {
  linkMove = event.target.closest("a");
});

document.addEventListener("copy", async function (event) {
  const selection = document.getSelection();
  if (selection && selection.toString().trim()) {
    return; // 有选中的内容,直接返回,不修改剪贴板内容
  }

  if (linkMove) {
    copy(linkMove.textContent, linkMove.href);
  } else {
    copy(document.title, window.location.href);
  }
  event.preventDefault(); // 阻止默认的复制行为
});

document.addEventListener("contextmenu", function (event) {
  linkMenu = event.target.closest("a");
});

function getLinkText(linkUrl) {
  return linkMenu ? linkMenu.textContent : linkUrl;
}

chrome.runtime.onMessage.addListener(
  // background 发送过来的消息处理程序
  function (request, sender, sendResponse) {
    if (request.message === "copyLink") {
      copy(request.title || getLinkText(request.url), request.url);
    } else if (request.message === "copyLinkText") {
      navigator.clipboard.writeText(
        request.title || getLinkText(request.linkUrl)
      );
    }
  }
);
background.js:
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "copyLink",
    title: "复制链接",
    contexts: ["link"],
  });
  chrome.contextMenus.create({
    id: "copyLinkText",
    title: "复制链接文本",
    contexts: ["link"],
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (
    !info.linkUrl ||
    ["copyLink", "copyLinkText"].indexOf(info.menuItemId) == -1
  ) {
    return;
  }

  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {
      message: info.menuItemId,
      title: info.selectionText || info.linkText,
      url: info.linkUrl,
    });
  });
});