内容脚本 运行 是在同一个孤立的世界中,还是在不同的孤立世界中?

Do content scripts run in the same isolated world, or in separate isolated worlds?

我正在通读 Chrome 文档,试图了解如何创建扩展,并且正在努力了解如何在内容脚本之间共享数据。

假设我的扩展捆绑了三个脚本:

jquery.js
script1.js
script2.js

我需要script1.jsscript2.js才能使用jQuery,每个脚本都需要能够读写全局变量alawindow.foo = 'bar'

脚本还向事件驱动的 DOM 添加内容,因此只要选项卡打开,它们 read/write 的全局变量就需要保持不变。

例如,script1.js 可能会在页面上添加一个按钮,单击该按钮时 运行 是 script1.js 中定义的一个函数,该函数依次设置一个全局变量,然后 运行 是 script2.js 中的一个函数,然后使用该变量(只是一个例子)。

The content script docs 说:

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

这是否意味着扩展的内容脚本根本无法相互交互,或者说来自不同 扩展的内容脚本无法相互交互?

换句话说,所有扩展内容脚本 运行 是在同一个孤立的世界中,还是在不同的孤立世界中?

每个扩展,每帧有一个执行上下文。

如果您在同一个框架中注入多个脚本,它们将完全共享上下文(查看彼此的变量等)

DOM 在所有上下文中共享。这使得与 custom events.

的跨上下文通信成为可能

跨框架(或交叉表)通信通常需要后台脚本作为消息代理或类似 window.postMessage