Chrome扩展:保留popup.html时无法从后台脚本向内容脚本发消息
default_popup Is Configured Hey there! Let's break down why your message isn't getting through when you have a default_popup set in your Chrome extension, and how to fix it.
The Root Cause
When you add a default_popup to your browser_action in manifest.json, Chrome changes how the browser action button behaves:
- Instead of triggering the
chrome.browserAction.onClickedlistener in your background script, clicking the button directly opens the popup - Since that listener never runs, the code that sends the message to your content script never executes—which is exactly why removing the popup makes everything work again!
The Fix: Move Message Logic to the Popup
The simplest solution is to handle the message sending from the popup itself. Here's how to adjust your code step by step:
Update
popup.htmlto include a script file
Add a script tag (and optional UI element) to your popup to trigger the message:<!-- html/popup.html --> <!DOCTYPE html> <html> <head> <title>Find leads</title> <style> body { width: 200px; padding: 10px; margin: 0; } button { width: 100%; padding: 8px; cursor: pointer; } </style> </head> <body> <p>Click to start lead search!</p> <button id="triggerBtn">Send Message</button> <script src="js/popup.js"></script> </body> </html>Create
popup.jsto send the message
This script will listen for a button click and send the message to the active tab's content script:// js/popup.js document.addEventListener('DOMContentLoaded', () => { const triggerBtn = document.getElementById('triggerBtn'); triggerBtn.addEventListener('click', () => { // Grab the active tab in the current window chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { const activeTab = tabs[0]; // Send the message to the content script chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"}); // Optional: Close the popup after sending window.close(); }); }); });Fix the undefined variable in
content.js
Your current content script usesfirstHrefwithout defining it—this will throw an error. Add a definition for it (customize based on your needs):// js/content.js chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if( request.message == "clicked_browser_action" ) { console.log("Congratulations you can now work!"); // Define firstHref (example: get the first link on the page) const firstHref = document.querySelector('a')?.href || 'https://example.com'; chrome.runtime.sendMessage({"message": "open_new_tab", "url": firstHref}); } } );Keep your
manifest.jsonas-is
You don't need to remove thedefault_popupconfiguration anymore—it will work perfectly alongside the new popup logic.
Why This Works
Now when you click the browser action button, the popup opens. Clicking the button inside the popup triggers the message send logic, which reaches your content script just like you intended.
内容的提问来源于stack exchange,提问作者Landry

