我想创建一个包应用程序 chrome 扩展,以允许用户编写和执行 javascript 代码(如 javascript 控制台)。
我想使用eval()
函数来执行JS代码。
经典的 javascript eval
函数在从 Chrome 扩展调用时会抛出错误:
Uncaught Error: Code generation from strings disallowed for this context
要在 Chrome 扩展中使用 eval
,人们需要使用 sandbox ,但是当我在 list 中写入沙箱时,我收到此错误:
There were warnings when trying to install this extension: 'sandbox' is not allowed for specified package type (theme, app, etc.).
更新
根据this issue ,软件包应用程序不支持沙箱,所以我有两个问题:
是否可以使用另一种方法来代替
eval()
?是否可以在没有沙箱的情况下使用
eval
? (我想可能不是出于安全原因?)
最佳答案
更新:
至少自 2013 年 1 月起,Chrome 现在允许 unsafe-eval
内容安全策略 (CSP) 指令,允许在沙箱外部执行 eval
:
The policy against
eval()
and its relatives likesetTimeout(String)
,setInterval(String)
, andnew Function(String)
can be relaxed by adding'unsafe-eval'
to your policy
添加适当的CSP给您的扩展 list ,例如:
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
<小时/>
bug you refer to现已标记为已修复
,并自 Chrome 22 起包含在内。
在引入 'unsafe-eval'
之前,无法让 manifest_version: 2
扩展的 CSP 允许将任意文本作为代码执行。 At the time ,Google 明确表示无法取消此限制(在沙箱之外):
Inline JavaScript, as well as dangerous string-to-JavaScript methods like
eval
, will not be executed... There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includesunsafe-inline
will have no effect. This is intentional.
如上所述,现在可以放宽此限制。
关于javascript - chrome 包应用程序中的 eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11897112/