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

Chrome扩展报错:Uncaught TypeError及选中文本同步至Popup功能问题

问题排查与需求实现

问题描述

点击Buy按钮时,期望将页面选中的文本显示在popup.html的ext元素中,但出现错误:Uncaught TypeError: Cannot read properties of undefined (reading 'sendMessage'),报错位置在content.js第13行。

错误分析

  1. sendMessage调用逻辑错误:原content.js监听鼠标选中文本后主动向后台发送消息,但该操作并非需求所需,且后台未处理此类消息;更关键的是,需求的核心是popup主动获取页面选中内容,而非content script主动推送。
  2. 数据流转逻辑偏离:原popup点击按钮后仅向后台发送固定的"Hello"消息,后台返回相同内容,完全未涉及页面选中文本的获取与传递。

修正方案与代码实现

正确流程:点击Buy按钮 → Popup向当前活跃标签的content script发送请求 → Content script获取选中文本并返回 → Popup接收数据并展示。

修正后的各文件代码

manifest.json(无需修改)

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

popup.js(修改为向content script请求数据)

const btn = document.getElementById('btn');
btn.addEventListener('click', async () => {
    // 获取当前活跃标签页
    const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    // 向目标标签的content script发送请求
    chrome.tabs.sendMessage(tab.id, {action: "getSelectedText"}, (response) => {
        const extElement = document.getElementById('ext');
        extElement.textContent = response?.selectedText || "未选中任何文本";
    });
});

content.js(添加监听Popup请求的逻辑)

console.log('content script loaded');

// 监听来自Popup的消息请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "getSelectedText") {
        const selectedText = window.getSelection().toString().trim();
        sendResponse({selectedText: selectedText});
    }
});

background.js(简化为仅保留必要监听,当前需求无需额外逻辑)

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    // 可根据后续需求添加后台处理逻辑
});

关键说明

  • 使用chrome.tabs.sendMessage而非chrome.runtime.sendMessage,因为content script属于特定标签页,需指定tab ID才能准确通信。
  • 移除content.js中主动发送消息的冗余逻辑,改为被动响应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 10:54:14