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

Chrome扩展无法在Content Script中打印OnMessage接收的消息

Hey there, let's break down why your message isn't showing up in the console and fix it step by step!

First, let's identify the key issues in your code

  1. You're loading content.js in your popup (wrong context)
    Your popup.html includes <script type="module" src="content.js"></script> — but content scripts are meant to be injected into web pages, not run in the popup's isolated context. This doesn't help your message passing, and it's likely causing confusion between different console environments.

  2. Missing error handling in message sending
    You're not checking if the message was sent successfully from the background, which makes it hard to debug why the content script isn't receiving it.

  3. Easy to mix up console contexts (a super common newbie pitfall!)
    Content script logs show up in the web page's developer tools console, not the extension's background or popup console. Make sure you're looking in the right place!


Fixed Code Examples

Let's adjust your code to fix these issues:

1. Updated background.js (with error logging)

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
  // Only send messages to fully loaded http/https pages (matches your content script's scope)
  if (info.status === "complete" && /^https?:/.test(tab.url)) {
    console.log("Attempting to send message to tab:", tabId);
    chrome.tabs.sendMessage(tabId, {action: "test", message: tab.url}, (response) => {
      // Catch errors like missing content scripts or closed tabs
      if (chrome.runtime.lastError) {
        console.error("Failed to send message:", chrome.runtime.lastError.message);
      } else {
        console.log("Message sent successfully!");
      }
    });
  }
});

2. Tweaked content.js (more verbose logging for debugging)

console.log("before method");

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("Received message from background:", message);
  if (message.action === "test") {
    console.log("Test message content - URL:", message.message);
  }
  // Uncomment below if you want to send a response back to the background
  // sendResponse({status: "received", data: "got it!"});
});

console.log("after method, message listener is active");

3. Cleaned up popup.html (removed invalid content.js reference)

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style>
    body { width: 200px; padding: 10px; }
  </style>
</head>
<body>
  <p>Extension Test Popup</p>
  <!-- Add your own popup.js here if you need popup interactions, NOT content.js -->
  <!-- <script src="popup.js"></script> -->
</body>
</html>

Debugging Steps to Verify

  1. Reload your extension: Go to chrome://extensions/, enable Developer Mode, and click the "Reload" button for your extension.
  2. Check the right console:
    • For content script logs: Open a web page (like https://example.com), press F12 to open the page's developer tools, and go to the Console tab.
    • For background logs: Go back to chrome://extensions/, click "Background page" under your extension to open its console.
  3. Test with a fresh tab: Open a new tab and navigate to any http/https site — you should see the message logs in both the page's console and the background console.

Quick Recap of Newbie Pitfalls to Avoid

  • Context confusion: Content scripts live in web pages, background scripts in the extension's backend, and popups in their own isolated window. Each has its own console.
  • Don't reuse content.js in popups: Content scripts are injected automatically via the manifest; popups need their own separate scripts if they need logic.
  • Always handle errors: Using chrome.runtime.lastError will save you hours of guessing why messages aren't going through.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:24:05