You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展开发中如何从右键点击的URL中提取两个参数作为变量

Chrome扩展实现osu链接参数提取方案

1. 前置配置(manifest V3版本)

首先在扩展的manifest.json中声明所需权限和后台服务配置:

{
  "manifest_version": 3,
  "name": "osu参数提取工具",
  "version": "1.0",
  "permissions": ["contextMenus", "activeTab"],
  "background": {
    "service_worker": "background.js"
  }
}

2. 核心逻辑实现(background.js)

2.1 注册右键菜单

仅当用户右键点击超链接时显示提取菜单:

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "extractOsuBeatmapParams",
    title: "提取beatmap参数",
    contexts: ["link"]
  })
})

2.2 监听点击事件提取参数

点击菜单后用正则匹配提取两组数字,分别赋值给sid和bid:

chrome.contextMenus.onClicked.addListener((info) => {
  if (info.menuItemId !== "extractOsuBeatmapParams") return
  const targetLink = info.linkUrl
  // 按osu beatmap链接固定结构匹配数字
  const matchRes = targetLink.match(/beatmapsets\/(\d+)#osu\/(\d+)/)
  if (!matchRes) return
  // 赋值变量,可直接在后续逻辑中使用
  const sid = matchRes[1]
  const bid = matchRes[2]
  // 测试输出,可替换为你自己的业务逻辑
  console.log(`sid:${sid}, bid:${bid}`)
})

正则说明

使用的/beatmapsets\/(\d+)#osu\/(\d+)/正则通过固定路径前缀定位参数,两个(\d+)捕获组分别匹配sid和bid,避免误匹配其他结构的链接。


内容的提问来源于stack exchange,提问作者BlaNKtext

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:39:02