N
N
newaitix2021-03-09 00:24:32
JavaScript
newaitix, 2021-03-09 00:24:32

How to pass message from background to content?

So I'm trying to convey a message.
background.js

chrome.tabs.sendMessage(tab.id,{content: "message"},function(response){});

This is how I am trying to get the
content.js message
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    console.log(request)
});

This is what the manifest looks like.
"background":{
    "scripts":[
      "js/background.js"
    ],
    "persistent":false
  },
  "options_ui":{
    "open_in_tab":true,
    "page":"html/options.html"
  },
  "chrome_url_overrides":{
    "newtab":"html/newpage.html"
  },
  "permissions":[
  ]

content.js is included in "html/newpage.html"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
med1um, 2021-04-02
@med1um

In your code, it is not enough just to specify: which tab you want to send the message to.
There are a lot of tabs. I usually have a couple dozen :)
So you need to define the tab object in the tab.id expression before sending the message.
For example, if you want to send a message to the active tab, then tab can be defined like this:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var tab = tabs[0];
  chrome.tabs.sendMessage(tab.id, {content: "message"}, function(response) {});
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question