Recently I've been noticing lots of errors related to "Receiving end does not exist". My code currently uses lots of "chrome.tabs.sendMessage()" calls to automate filling in some text fields on forms.
Current setup:
background.js (in chrome.tabs.onUpdated.addListener routine): chrome.tabs.sendMessage(
tab.id, dataArray, callBack);
content_load.js (in which is a content_script in Manifest): chrome.runtime.onMessage.addListener(() => { });
Now, I don't always need to use a callback method, so having the content script not return anything is an issue that triggers the error mentioned above. Having the content script always return something fixes it. However, even after closing tabs I see the error pop up. My scripts run quite a bit on the same tab, and from my reading, it seems like using the ports api would be better for longevity of message passing.
Am I understanding correctly that the above only sends the message to the 1 tab?
If I start migrating my code to use ports, I don't see anyway for a port to exist on 1 tab and only send to that tab? How does my background script know which tab/port to post a message to?
New setup:
background.js:
var _port = null;
chrome.runtime.onConnect.addListener(function(port) { _port = port); });
chrome.tabs.onUpdated.addListener(() => { _port.postMessage({'hello from port'}); });
content_load.js:
var port = chrome.runtime.connect({name: 'test'});
port.onMessage.addListener(function(msg) { console.log(msg); });
The new setup does indeed work, however I don't know if it's actually better. I don't ever need message passing to be cross-tab, so I don't know if the port things are tab specific? If I use the script on a couple of different tabs at the same time, do things route correctly? My current setup does because of the tab specific message sending...