You need to enable JavaScript to run this app. 如何开发Chrome扩展获取当前URL并传递给C# Windows Forms应用
优惠活动
大模型
产品
解决方案
定价
更多

如何开发Chrome扩展获取当前URL并传递给C# Windows Forms应用

一、Chrome扩展(Manifest V3)实现URL变化监听

你现有代码的核心问题如下:

  • Manifest配置文件后缀应为manifest.json,不是manifest.js
  • Service Worker(background.js运行环境)没有window对象,无法调用alert、无法挂载全局函数到window上
  • Content Script(app.js运行在页面沙箱中)权限受限,无法直接调用chrome.tabs类的扩展核心API

1. 修正后的manifest.json

{
  "manifest_version": 3,
  "name": "URL collector",
  "version": "0.11",
  "description": "采集当前浏览器访问URL",
  "permissions": [
    "tabs"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

仅需要tabs权限即可监听标签页相关事件,不需要多余的权限配置。

2. 正确的background.js代码

// 监听标签切换事件
chrome.tabs.onActivated.addListener(async (activeInfo) => {
  const tab = await chrome.tabs.get(activeInfo.tabId);
  if (tab.url) {
    console.log("当前URL(标签切换):", tab.url);
    // 后续这里加发送URL到WinForms的逻辑
  }
});

// 监听标签页URL更新事件(覆盖页面跳转、SPA路由变化、刷新等所有场景)
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  // 只处理URL变化的事件回调
  if (changeInfo.url && tab.active) {
    console.log("当前URL(页面变化):", changeInfo.url);
    // 后续这里加发送URL到WinForms的逻辑
  }
});

不需要Content Script就能覆盖所有URL变化场景,直接在后台Service Worker中监听Chrome原生事件即可,测试时可以在扩展管理页点击对应扩展的「服务工作进程」打开调试控制台查看输出日志。

扩展开发学习建议

直接查阅Chrome官方扩展开发文档即可,优先看Manifest V3的基础概念、核心API说明、事件监听机制相关的内容,入门门槛不高,你有JS基础很快就能上手。


二、Chrome扩展与C# WinForms通信方案

最优方案是WinForms启动本地环回HTTP服务,扩展主动推送URL,实现简单、稳定性高、不需要额外的系统权限配置,具体实现逻辑:

1. WinForms端实现本地HTTP监听

用.NET内置的HttpListener即可,不需要引入第三方依赖,示例代码:

using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class MainForm : Form
{
    private HttpListener _httpListener;
    public MainForm()
    {
        InitializeComponent();
        // 启动本地HTTP监听,端口选一个未被占用的即可,比如18080
        StartHttpListener();
    }

    private async void StartHttpListener()
    {
        _httpListener = new HttpListener();
        _httpListener.Prefixes.Add("http://127.0.0.1:18080/url-receive/");
        _httpListener.Start();
        while (_httpListener.IsListening)
        {
            var context = await _httpListener.GetContextAsync();
            // 接收扩展POST过来的URL
            if (context.Request.HttpMethod == "POST")
            {
                using var reader = new System.IO.StreamReader(context.Request.InputStream, Encoding.UTF8);
                var url = await reader.ReadToEndAsync();
                // 这里把URL更新到窗体控件上,注意跨线程调用
                this.Invoke(new Action(() => {
                    // 比如你的文本框名是txtCurrentUrl
                    txtCurrentUrl.Text = url;
                }));
            }
            // 返回响应给扩展
            context.Response.StatusCode = 200;
            context.Response.Close();
        }
    }

    // 窗体关闭时停止监听
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        _httpListener?.Stop();
        _httpListener?.Close();
    }
}

2. Chrome扩展端推送代码

在刚才的background.js的事件回调里加发送逻辑即可:

// 封装发送URL到WinForms的方法
async function sendUrlToWinForms(url) {
  try {
    await fetch("http://127.0.0.1:18080/url-receive/", {
      method: "POST",
      body: url,
      mode: "no-cors" // 避免跨域错误
    });
  } catch (e) {
    // WinForms未启动时忽略错误即可
  }
}

// 标签切换的回调调用
chrome.tabs.onActivated.addListener(async (activeInfo) => {
  const tab = await chrome.tabs.get(activeInfo.tabId);
  if (tab.url) {
    console.log("当前URL(标签切换):", tab.url);
    await sendUrlToWinForms(tab.url);
  }
});

// URL更新的回调调用
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (changeInfo.url && tab.active) {
    console.log("当前URL(页面变化):", changeInfo.url);
    await sendUrlToWinForms(changeInfo.url);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:54:07