5

I'm reading through the Chrome docs trying to learn how to create an extension and am struggling to understand how to share data between content scripts.

Let's say I have three scripts bundled with my extension:

jquery.js
script1.js
script2.js

I need script1.js and script2.js to use jQuery, and each script needs to be able to read and write global variables ala window.foo = 'bar'.

The scripts also add content to the DOM that is event driven, so the global variables they read/write need to be persistent as long as the tab is open.

For example, script1.js might add a button to the page that when clicked runs a function defined in script1.js, which in turn sets a global variable and then runs a function in script2.js which then uses that variable (just an example).

The content script docs say:

However, content scripts have some limitations. They cannot:

  • ...
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

Does this mean an extension's content scripts cannot interact with each other at all, or is it saying that content scripts from different extensions can't interact with each other?

In other words, do all of an extensions content scripts run in the same isolated world, or in separate isolated worlds?

Nate
  • 26,164
  • 34
  • 130
  • 214

1 Answers1

6

There is one execution context per extension, per frame.

If you inject several scripts in the same frame, they will share context fully (see each others' variables, etc.)

DOM is shared across all contexts. That enables cross-context communication with custom events.

Cross-frame (or cross-tab) communication will normally require a background script as a proxy for messages or something like window.postMessage.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206