adam-p / markdown-here

Google Chrome, Firefox, and Thunderbird extension that lets you write email in Markdown and render it before sending.
https://markdown-here.com
MIT License
59.64k stars 11.26k forks source link

Chrome: detect failed background script communication #121

Open adam-p opened 11 years ago

adam-p commented 11 years ago

There seem to be two cases when requests from the content script to the background script can fail:

I think that the failure can be detected by undefined being returned to a get-options request, say.

So...

adam-p commented 10 years ago

Mario Feaster (@ShamariFeaster) suggested a very good solution via email:


My solution for problems like this is to use chrome.tabs.executeScript() when chrome.tabs.onTabActivated() and chrome.tabs.onTabUpdated() fires. But to protect against having a content script stranded without ports, as soon as a port is opened, I attach port.onDisconnected() and re-execute script when that event fires.

I also use a class I made called PortManager. It contains a map structure I call tabToPortMap. It looks like this < tabId:string, port_objects:array >.

I listen for chrome.runtime.onConnect() and when that fires, I add that port object to tabToPortMap that’s keyed on the tabId of the tab where the script was executed.

When I want to send a message to a tab, I get it’s available ports from tabToPortMap and then cycle through them, sending a message to each one. Since I have set this system up I’ve never had an instance of stranded content scripts.