1

background script:

let msg = 'ty for help';

chrome.browserAction.onClicked.addListener(function (event) {
    console.log('clicked');
    chrome.tabs.executeScript(null, {
        file: 'js/content.js', /* my content script */   }, () => {
            connect(msg) //this is where I call my function to establish a connection     
        });
    });
});

function connect(msg) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const port = chrome.tabs.connect(tabs[0].id);
        port.postMessage(msg);
    });
}

content script:

chrome.runtime.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(show_floater) {
        console.log('why do I get printed more than once per click?????');
    });
});

The behaviour I'd like is for the code of my content script to be executed ONCE every time the user clicks on the extension icon of the browser. As of now for every click it is called multiple times. Here, under port lifetime it says that onConnect may be called for all the frames. I tried to set all_frames to false in the manifest but nothing changes... send help D:

Stefano Pozzi
  • 529
  • 2
  • 10
  • 26
  • Every time the user clicks on your browserAction icon, a new copy of your content script is injected, which adds another listener. – Iván Nokonoko Nov 24 '20 at 15:55
  • @IvánNokonoko I make sure to inject in the DOM only once if that is what you are referring to. Or are you talking about the actual listeners? Because even at the first click it gets called multiple times – Stefano Pozzi Nov 24 '20 at 15:58
  • 1
    If you have `content_scripts` in manifest.json then you already have a content script running automatically. – wOxxOm Nov 24 '20 at 17:08
  • See also [Chrome extension: Checking if content script has been injected or not](https://stackoverflow.com/a/34529045) – wOxxOm Nov 24 '20 at 17:09
  • @wOxxOm you save the day twice. I am and imbecile... I did have the contents script in both manifest and injecting it.... ty sir – Stefano Pozzi Nov 24 '20 at 17:12
  • @wOxxOm sad news, still runs multiple times even if i removed it from the manifest. I forgot that before leaving work I fixed the issue by checking if the DOM element exist before removing it (workaround)... – Stefano Pozzi Nov 24 '20 at 17:22

1 Answers1

0

I had the content script in the manifest and I would also inject it through the above code...

Stefano Pozzi
  • 529
  • 2
  • 10
  • 26