Components.utils.evalInWindow 编辑
This function is no longer available as of Firefox 34. See bug 1042840 for details.
This function enables code running in a more-privileged JavaScript context to evaluate a string in a less-privileged JavaScript context. The result is structured cloned back to the original context, unless it is native (for example, if it returns a DOM node, this is not structured cloned, because the original context will see that through an XrayWrapper already), so it's guaranteed to behave predictably.
This is useful for privileged code, such as add-on code, to access variables and APIs defined in web content.
Even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected).
This function is made available as a global in sandboxes which have the wantExportHelpers
option set in the Sandbox()
constructor.
Syntax
var result = Components.utils.evalInWindow(script, window);
Parameters
script : string
- The script to evaluate in the other window.
window : object
- The window in which to evaluate the script.
Returns
The result of evaluating the script. If this is just native (for example, a DOM node), then the function relies on XrayWrappers to wrap the returned content, otherwise the result is structured-cloned.
This does impose some restrictions on the sorts of things that can be returned: in particular, the result can't contain any functions, because functions can't be structured-cloned.
Example
Suppose a page script defines a variable:
// page-script.js
var someLocalVariable = {
name: "selection1",
node: document.documentElement
};
An add-on script or other privileged script can access the variable using evalInWindow()
:
// add-on-script.js
var result = Components.utils.evalInWindow("someLocalVariable", contentWindow);
console.log(result);
// {"name":"selection1","node":{}}
The add-on code can modify the variable as well, of course:
// add-on-script.js
Components.utils.evalInWindow("someLocalVariable.newProp = 42", contentWindow);
// page-script.js
console.log(window.someLocalVariable.newProp);
// 42
But note that the add-on script must trust that the page script has not redefined the setter on someLocalVariable
: unlike XrayWrappers, evalInWindow()
does not provide x-ray vision.
If the returned object contains a function, calls to evalInWindow()
will throw an error:
// page-script.js
function bar() {
}
var someLocalVariableContainingAFunction = {name: "selection1", foo : bar};
// add-on-script.js
Components.utils.evalInWindow("someLocalVariableContainingAFunction", contentWindow);
// ERROR, function can't be cloned
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论