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

Chrome扩展消息传递无输出:content.js向popup.js传值问题求助

问题分析

你的代码存在几个关键错误导致消息传递失败:

  • 通信逻辑颠倒:content script一加载就主动发送消息,但此时popup可能未打开,消息直接丢失;正确流程应为popup打开后主动向content script请求数据。
  • background.js逻辑错误:监听函数嵌套了另一个onMessage函数,实际未处理任何消息;且你无需通过background中转,popup可直接与content script通信。
  • Manifest V3 API误用:chrome.extension.getBackgroundPage()在Manifest V3中已废弃(service worker无DOM),该代码无效。
  • 消息格式不匹配:content script发送纯字符串,而popup期望接收带特定字段的响应,格式不兼容。

修正后的代码

1. manifest.json(简化核心配置)

移除不必要的background和activeTab权限:

{
    "name": "hoko's ext",
    "description": "my ext",
    "version": "1.0",
    "manifest_version": 3,
    "action": {
        "default_popup": "popup.html" 
    },
    "content_scripts": [
        {
            "matches": ["https://*/*", "http://*/*"],
            "js": ["content-script.js"]
        }
    ],
    "permissions": ["tabs"]
}

2. content-script.js(添加消息监听响应逻辑)

移除无用的注入脚本代码(若后续需要可保留),添加监听popup请求的逻辑:

// 监听来自popup的消息请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "getPageTitle") {
        // 获取页面标题并返回
        const pageTitle = document.title;
        sendResponse(pageTitle);
    }
});

// 若需保留注入脚本逻辑可取消注释
// function injectScript(file_path, tag) {
//     var node = document.getElementsByTagName(tag)[0];
//     var script = document.createElement('script');
//     script.setAttribute('type', 'text/javascript');
//     script.setAttribute('src', file_path);
//     node.appendChild(script);
// }
// injectScript(chrome.runtime.getURL('inject.js'), 'body');

3. popup.js(主动请求并显示数据)

移除废弃API,添加错误处理确保消息传递成功:

window.addEventListener('DOMContentLoaded', () => {
    const contentElement = document.getElementById('extensionpopupcontent');
    
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        if (!tabs[0]) {
            contentElement.textContent = "无激活标签";
            return;
        }
        // 向content script发送请求
        chrome.tabs.sendMessage(tabs[0].id, {action: "getPageTitle"}, (response) => {
            if (chrome.runtime.lastError) {
                contentElement.textContent = "无法获取标题:" + chrome.runtime.lastError.message;
                return;
            }
            contentElement.textContent = response;
        });
    });
});

4. 可选清理

若无需中转或注入功能,可直接删除background.js和inject.js,避免冗余。

验证步骤

  1. 在chrome://extensions/页面重新加载扩展
  2. 打开任意http/https页面
  3. 点击扩展图标打开popup,即可看到当前页面标题显示在弹窗中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:15:32