如何监听网页按钮触发的复制事件?Chrome扩展开发问题
解决Reddit复制链接自动转短链接的Chrome扩展方案
核心思路
网页按钮触发的复制通常用navigator.clipboard.writeText或execCommand('copy')实现,普通copy事件监听可能覆盖不全。我们需要同时处理这两种复制场景,确保无论哪种方式复制Reddit链接,都能自动替换成短链接。
步骤1:搭建扩展文件结构
创建一个文件夹,包含两个核心文件:
manifest.json(扩展配置文件)content.js(注入到Reddit页面的处理脚本)
步骤2:配置manifest.json
这是Chrome扩展的核心配置,指定扩展信息和注入规则:
{ "manifest_version": 3, "name": "Reddit短链接转换器", "version": "1.0", "description": "复制Reddit链接时自动转为redd.it短链接", "content_scripts": [ { "matches": ["https://*.reddit.com/*"], "js": ["content.js"] } ] }
步骤3:编写content.js处理逻辑
同时覆盖两种复制场景,确保所有Reddit链接复制都能被拦截替换:
// 拦截navigator.clipboard.writeText方式的复制 const originalWriteText = navigator.clipboard.writeText; navigator.clipboard.writeText = async function(text) { // 检查是否为Reddit帖子链接 if (text.startsWith('https://www.reddit.com/')) { const postIdMatch = text.match(/comments\/(\w+)\//); if (postIdMatch) { // 生成标准redd.it短链接 const shortUrl = `https://redd.it/${postIdMatch[1]}`; return originalWriteText.call(this, shortUrl); } } // 非Reddit链接按原逻辑执行 return originalWriteText.call(this, text); }; // 拦截execCommand('copy')方式的复制 document.addEventListener('copy', function(e) { const copiedText = window.getSelection().toString(); if (copiedText.startsWith('https://www.reddit.com/')) { const postIdMatch = copiedText.match(/comments\/(\w+)\//); if (postIdMatch) { const shortUrl = `https://redd.it/${postIdMatch[1]}`; // 修改剪贴板内容 e.clipboardData.setData('text/plain', shortUrl); // 阻止默认复制行为 e.preventDefault(); } } }, true); // 捕获阶段监听,避免被页面事件阻止
步骤4:加载扩展到Chrome
- 打开Chrome浏览器,输入
chrome://extensions/进入扩展管理页面 - 开启右上角的「开发者模式」
- 点击「加载已解压的扩展程序」,选择你创建的扩展文件夹
关键说明
- 双拦截覆盖:同时处理Reddit分享按钮常用的
navigator.clipboard.writeText,以及右键复制等场景的execCommand('copy') - 短链接生成逻辑:从原链接提取帖子ID(
comments/后的一串字符),拼接成https://redd.it/帖子ID的标准格式 - 兼容性:基于Chrome扩展Manifest V3,适配最新版本浏览器
内容的提问来源于stack exchange,提问作者haoyu
相关产品推荐
相关产品推荐

