Why chrome.tabs.sendmessage doesn't accept the parameter of message?

Viewed 176

I want to send the selected text value to my content script from the background script. Here is the code I use:

chrome.contextMenus.create({ 
  id: "TranslationFetcher",
  title: "Translate this word",
  contexts: ["selection"]
});


chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
      chrome.tabs.sendMessage(tabs[0].id, {message: info.selectionText}, {type: "getTranslation"});
  });
});

However, when I run the above code without the message parameter, the expected request is being passed to the content script.

How to resolve this error? and how to send the selected text to the content script?

1 Answers

It is my bad I separate the message object. I figured it out. The answer is:

chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
      chrome.tabs.sendMessage(tabs[0].id, {type: "getTranslation", message: info.selectionText});
  });
});
Related