Components.utils.createObjectIn
creates a new JavaScript object in the scope of the specified object's compartment.
This function is made available as a global in sandboxes which have the wantExportHelpers
option set in the Sandbox()
constructor.
Note that this function is now mostly obsolete when you are using Sandbox, because you can create an object in a different compartment using new
. For example, to create a new object in the compartment identified by contentWindow:
var newObject = new contentWindow.Object();
But it is really needeed from Firefox 30 onwards when trying to manipulate the DOM window. See details in https://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/.
var newObject = Components.utils.createObjectIn(obj, options);
obj
options
defineAs
, which determines the name of the object in the target compartment.A new object in the specified scope.
To create a new object in the scope of a specified DOM window, you can simply do:
function genPropDesc(value) { return { enumerable: true, configurable: true, writable: true, value: value }; } var myObject = Components.utils.createObjectIn(myWindow); var propList = { name: genPropDesc("name"), date: genPropDesc("date"), id: genPropDesc("id"), func: genPropDesc(function() { alert("Called func!"); }) }; Object.defineProperties(myObject, propList); Components.utils.makeObjectPropsNormal(myObject);
This sets up the new object in the scope of the object myWindow
, then adds properties by calling Object.defineProperties()
, then normalizes them by calling Components.utils.makeObjectPropsNormal()
.
To create an object with a specified name, use defineAs
:
var foo = Components.utils.createObjectIn(myWindow, {defineAs: "foo"});
Now the target compartment's window has a new global object named foo
.