Sharing objects between content-scripts

Hi guys, I’m wondering if there is a way to share object(s) between content-scripts attached to the same tab via tab.attach method.

Example flow:

  1. User clicks on ActionButton -> I’m attaching jQuery script and Primary script via tab.attach to the active tab;
  2. Getting message in a background, that Primary script and jQuery are loaded -> attaching Secondary script to the same active tab.

After the Secondary script attached to the tab how do I use its variables from Primary script? And how do I access jQuery from Secondary script?

I tried to do this too without realizing, content-scripts are running in a seperate process. You can’t share stuff between, can only send copies/clones.

The SDK is a strightjacket. You can do this with frame scripts, which are content scripts added using a non-SDK API. By default, frame scripts run in their own namespace, but you can set an option to have them share the global namespace and then you can easily share globals. Otherwise you have to establish communication via messages. Content scripts are essentially the same except that you can’t reasily control whether they get their own namespace. One exception is that all content scripts loaded in the same tab.attach share a single namespace!

So you have several types of message available. Perhaps the simplest is to send custom DOM events. These will be available for any script to listen on. You can also send messages using the SDK API (port/emit or post/receive). That doesn’t in itself give you shared access to shared objects, since the payload is copied, but it might be enough for you.

A sneaky way of sharing a generic javascript object is to attach it to a DOM element. Since all the scripts in that content process can see the DOM, they can all find the object. Note that page scripts won’t be able to see the object for security reasons, but you can use the unsafeWindow object to do some sharing between content and page scripts.

1 Like

Thank you guys for provided information. Actually I was able to share objects, I did it as described in a 3-rd -paragraph of Lithopsian’s response (via exportFunction to unsafeWindow), but I was sure it’s a tricky (incorrect) way and I faced an issue with prototypal inheritance, that’s why I was asking.

If it could be interesting to somebody - I decided to freeze development of my addon using FF add-ons SDK, 'cause it’s appeared much easier to port my chrome-extension to “WebExtensions” as it described on page https://developer.mozilla.org/en-US/Add-ons/WebExtensions.