内容脚本是在同一个孤立的世界中运行,还是在不同的孤立世界中运行? [英] Do content scripts run in the same isolated world, or in separate isolated worlds?

查看:115
本文介绍了内容脚本是在同一个孤立的世界中运行,还是在不同的孤立世界中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要 script1.js script2.js 使用jQuery,每个脚本都需要能够读取和写入全局变量ala window.foo ='bar'

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'.

脚本还向事件驱动的DOM添加内容,因此只要选项卡处于打开状态,它们读/写的全局变量就必须是持久的。

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.

例如, script1.js 可能会向页面添加一个按钮,单击该按钮时会运行 script1.js ,然后设置一个全局变量,然后在 script2.js 中运行一个函数,然后使用该变量(仅举例)。

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).

内容脚本文档说:


但是,内容脚本有一些限制。他们不能:

However, content scripts have some limitations. They cannot:


  • ...

  • 使用其分机页面定义的变量或函数

  • 使用由网页或其他内容脚本定义的变量或函数

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

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?

推荐答案

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

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在所有上下文中共享。这样可以与自定义事件进行跨上下文通信。

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

Cross -frame(或交叉表)通信通常需要后台脚本作为消息的代理或类似 window.postMessage

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

这篇关于内容脚本是在同一个孤立的世界中运行,还是在不同的孤立世界中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆