1

On button click, I'm trying to send message, but my listener is invoked multiple times.

popup.js:

chrome.tabs.sendMessage(tab.id, {action: "write", data: getData()}, function (response) { 
console.log(response,"!!!!");});

content.js:

chrome.runtime.onMessage.addListener(test);

function test(request, sender, sendResponse) {
  if (request.action === "write") {
     console.log("write");
  }
 return true;
}

Has anyone an idea what I am doing wrong?

Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
  • The question is incomplete: you need to show how you declare/inject content.js. You either have `"all_frames": true` or calling executeScript multiple times. – wOxxOm Oct 04 '20 at 06:44
  • This is how I have configured in manifest.json. ``` "content_scripts": [ { "matches": [ "https://*/*" ], "all_frames": false, "js": [ "scripts/content.js" ] } ]``` and I have this statement on button click. ```chrome.tabs.executeScript(null, {file: "scripts/content.js"});``` – Cheri Deepa Oct 04 '20 at 06:52
  • Remove chrome.tabs.executeScript - your script already runs automatically when you declare it in manifest.json. – wOxxOm Oct 04 '20 at 06:55
  • Thanks much, Its working but earlier I was getting this error, so I placed that statement there. 'Could not establish connection. Receiving end does not exist'. Any Idea why this error occurs. – Cheri Deepa Oct 04 '20 at 07:02
  • It means the content script wasn't running, which can happen if you reloaded the extension but forgot to reload the tab. Or the page was still loading and your content script doesn't have `"run_at": "document_start"`. See [Why am I getting an error when I click chrome extension?](https://stackoverflow.com/a/64153344) – wOxxOm Oct 04 '20 at 07:07
  • 1
    You can keep your current code if you add the listener in content.js conditionally: if (!chrome.runtime.onMessage.hasListeners()) chrome.runtime.onMessage.addListener(test); – wOxxOm Oct 04 '20 at 07:14
  • Sure, Thank you!! – Cheri Deepa Oct 04 '20 at 07:25

0 Answers0