0

I'm new to chrome extensions and I'm trying to send a message from the background script to the content script. However it keeps sending multiple messages and I don't know how to only send one.

manifest.json

{
  "name": "Example",
  "version": "1.0",
  "description": "Test Extension",
  "manifest_version": 2,
  "background": {
      "scripts": ["jquery-3.4.1.min.js","background.js"],
      "persistent": false
    },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "run_at": "document_start",
      "js": ["jquery-3.4.1.min.js","popup.js"]
    }
  ],
  "browser_action": {
    "default_popup": "popup.html",
    "default_title": "Testing"
  }
}

background.js

chrome.tabs.onUpdated.addListener(function(tabId,info, tab) {
  if (info.status == "complete") {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(tab.id, {action: "test", message: "test"}
    })

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.from == "message1") {
        console.log(message)
    }
      })
});

popup.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.action == "test"){
    chrome.runtime.sendMessage({from:"message1",message:message});
  }
});

Output:

{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
  • 1) onUpdated is invoked for all tabs, not just the active one. Remove query() and send the message to `tabId` which is already provided to you in parameters of the callback. An instance of the content script in that tab will receive the message. 2) `popup.js` is a misleading name and it usually means a browser_action popup's script in popup.html so you should use separate scripts for the popup script and the content script. 3) See also [Where to read console messages from background.js in a Chrome extension?](https://stackoverflow.com/a/10258029) – wOxxOm Mar 26 '20 at 06:36
  • Thank you so much! It works now @wOxxOm – user19573945 Mar 26 '20 at 15:38

0 Answers0