Search code examples
firefox-addon-sdk

Can two page mods on the same page share code?


Suppose I'm writing an extension that has two page mods that match different URL patterns, which sometimes overlap. If both page mods share some JS libs, is there a way for my extension to only load those shared JS libs into a particular page once and have both page mods use them?

It appears to me that each page mod that an extension loads into a page gets its own global scope/namespace, which thwarts code sharing. However, the documentation seems to indicate that content scripts in the same page should be able to access each other directly:

Content scripts loaded into the same document can interact with each other directly as well as with the web content itself.


Solution

  • Content scripts loaded into the same document can interact with each other directly as well as with the web content itself, as long as they are loaded in via the same PageMod instance.

    This is why PageMod's contentScriptFile option takes an array that can list several files, so that you can load in for example jQuery, and then use jQuery in your own separate code.

    What doesn't work is having some shared scope for multiple PageMod instances, as each PageMod is loaded into a separate sandbox.

    A possible wqorkaround would be to route messages from separate PageMod instances via the SDK's EventEmitter 'port' objects if you need simple communication.

    Unfortunately there is no way to share script resources between sandboxes as there is no shared cross-sandbox scope.