Interface nsIXPCComponents_UtilsType

interface of Components.utils

Hierarchy

Properties

Sandbox: nsIXPCComponents_utils_Sandbox

Cu.Sandbox is used to create a sandbox object

let sandbox = Cu.Sandbox(principal[, options]);

Using new Cu.Sandbox(...) to create a sandbox has the same effect as calling Cu.Sandbox(...) without new.

In JS, Cu.Sandbox uses the following parameters:

Param

The security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. The principal may be one of four types: the system principal, a content principal, an expanded principal or a null principal. Depending on the principal type, this argument can be a nsIPrincipal, a Window, a String, an Array or null. See below. A content principal can be provided by passing a nsIPrincipal, a DOM Window, or a string URI (not recommended). An expanded (or extended) principal is an array of principals, where each item can be either a nsIPrincipal, a DOM window or a string URI. A null principal can either be specified by passing null or created explicitly with Cc["@mozilla.org/nullprincipal;1"].createInstance(Ci.nsIPrincipal);

Param

Optional parameters, valid properties are:

  • allowWaivers: {Boolean} Allows the caller to waive Xrays, in case Xrays were used. Defaults to true.
  • discardSource: {Boolean} For certain globals, we know enough about the code that will run in them that we can discard script source entirely. A discarded source will be re-read when stringifying functions. Defaults to false.
  • forceSecureContext: {Boolean} Determines whether content windows and workers are marked as "Secure Context"s. If principal is the system principal, the value is forced to true. Otherwise defaults to false.
  • freshCompartment: {Boolean} Whether the sandbox should be created using a new compartment. Defaults to false.
  • freshZone: {Boolean} if true creates a new GC region separate from both the calling context's and the sandbox prototype's region. Defaults to false.
  • invisibleToDebugger: {Boolean} Whether this sandbox and its scripts can be accessed by the JavaScript Debugger. Defaults to false.
  • isWebExtensionContentScript: {Boolean} Whether this sandbox corresponds to a WebExtension content script, and should receive various bits of special compatibility behavior. Defaults to false.
  • metadata: {Object} Object to use as the metadata for the sandbox. See setSandboxMetadata.
  • originAttributes: {Object} Dictionary of origin attributes to use if the principal was provided as a string.
  • sameZoneAs: {Object} Javascript Object in whose garbage collection region the sandbox should be created. This helps to improve memory usage by allowing sandboxes to be discarded when that zone goes away. It also improves performance and memory usage by allowing strings to be passed between the compartments without copying or using wrappers. Content scripts should pass the window they're running in as this parameter, in order to ensure that the script is cleaned up at the same time as the content itself.
  • sandboxName: {String} Identifies the sandbox in about:memory. This property is optional, but very useful for tracking memory usage. A recommended value for this property is an absolute path to the script responsible for creating the sandbox. If you don't specify a sandbox name it will default to the caller's filename.
  • sandboxPrototype: {Object} Prototype object for the sandbox. The sandbox will inherit the contents of this object if it's provided. Passing a content window object, setting wantXrays:true (default) and using an extended principal provides a clean, isolated execution environment in which javascript code that needs Web APIs (such as accessing the window's DOM) can be executed without interference from untrusted content code.
  • userContextId: {Number} The id of the user context this sandbox is inside. Defaults to 0.
  • wantComponents: {Boolean} Indicates whether the Components object is available or not in the sandbox. If the sandbox interacts with untrusted content this should be set to false when possible to further reduce possible attack surface. Defaults to true.
  • wantExportHelpers: {Boolean} if true, then createObjectIn(), evalInWindow(), and exportFunction() are available in the sandbox. Defaults to false.
  • wantGlobalProperties: {Array} Each string is the name of an object that you want to make available as a global to code running in the sandbox. Possible values: Blob, ChromeUtils, CSS, CSSRule, Directory, DOMParser, Element, Event, File, FileReader, FormData, InspectorUtils, MessageChannel, Node, NodeFilter, PromiseDebugging, TextDecoder, TextEncoder, URL, URLSearchParams, XMLHttpRequest, XMLSerializer, atob, btoa, caches, crypto, fetch, indexedDB, rtcIdentityProvider
  • wantXrays: {Boolean} Whether the sandbox wants Xray vision with respect to same-origin objects outside the sandbox. Note that wantXrays is essentially deprecated. The preferred method of handling this now is to give the sandbox an expanded principal which inherits from the principal of the content compartment the sandbox will interact with. That lets the sandbox see the content compartment through X-ray wrappers, and gives any object passed from the sandbox to the content compartment opaque security wrappers unless export helpers are explicitly used. "Xray vision" is exactly the same Xray behavior that script always gets, by default, when working with DOM objects across origin boundaries. This is primarily visible for chrome code accessing content. However, it also occurs during cross-origin access between two content pages, since each page sees a "vanilla" view of the other. The protection is bidirectional: the caller sees the bonafide DOM objects without being confused by sneakily-redefined properties, and the target receives appropriate privacy from having its expandos inspected by untrusted callers. In situations where only unidirectional protection is needed, callers have the option to waive the X-ray behavior using wrappedJSObject or XPCNativeWrapper.unwrap(). In general, when accessing same-origin content, script gets a Transparent wrapper rather than an Xray wrapper. However, sandboxes are often used when chrome wants to run script as another origin, possibly to interact with the page. In this case, same-origin Xrays are desirable, and wantXrays should be set to true. Defaults to true.
isInAutomation: boolean
strict_mode: boolean

Bug 1621603 - Remove strict_mode.

Do not use this API! Instead use "use strict"; at the top of your JS file.

Methods

  • Increases the reference count for this interface. The associated instance will not be deleted unless the reference count is returned to zero.

    Returns

    The resulting reference count.

    Returns number

  • Parameters

    • aIID: object
    • Optional aInstancePtr: object

    Returns any

  • A run time mechanism for interface discovery.

    Returns

    NS_OK if the interface is supported by the associated instance, NS_NOINTERFACE if it is not.

    aInstancePtr must not be null.

    Parameters

    • aIID: object

      [in] A requested interface IID

    • aInstancePtr: object

      [out] A pointer to an interface pointer to receive the result.

    Returns void

  • Decreases the reference count for this interface. Generally, if the reference count returns to zero, the associated instance is deleted.

    Returns

    The resulting reference count.

    Returns number

  • API to dynamically block script for a given global. This takes effect immediately, unlike other APIs that only affect newly-created globals.

    The machinery here maintains a counter, and allows script only if each call to blockScriptForGlobal() has been matched with a call to unblockScriptForGlobal(). The caller must make sure never to call unblock() more times than it calls block(), since that could potentially interfere with another consumer's script blocking.

    Parameters

    • global: any

    Returns void

  • To be called from JS only.

    Call 'function', using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws. The function is called with no arguments, and 'this' is 'undefined'.

    The code in the function will see the given stack frame as the asyncCaller of its own stack frame, instead of the current caller.

    Parameters

    • _function: any
    • stack: nsIStackFrame
    • asyncCause: string

    Returns any

  • To be called from JS only.

    Do some cycle collector work, with the given work budget. The cost of calling Traverse() on a single object is set as 1. For testing.

    Parameters

    • budget: number

    Returns void

  • To be called from JS only.

    Reset the internal max slice time value used for getMaxCCSliceTimeSinceClear().

    Returns void

  • Clone an object into a scope. The 3rd argument is an optional options object:

    • cloneFunctions: boolean. If true, functions in the value are wrapped in a function forwarder that appears to be a native function in the content scope. Defaults to false.
    • wrapReflectors: boolean. If true, DOM objects are passed through the clone directly with cross-compartment wrappers. Otherwise, the clone fails when such an object is encountered. Defaults to false.

    Parameters

    • value: any
    • scope: any
    • options: any

    Returns any

  • Returns void

  • To be called from JS only. C++ callers should use the nsCycleCollector_createLogger() function instead.

    Create an instance of the built-in cycle collector logger object.

    Returns nsICycleCollectorListener

  • Create a commandline object.

    Returns

    a new nsICommandLine instance.

    Parameters

    • args: invalid

      The arguments of the command line, not including the app/program itself.

    • workingDir: nsIFile

      An optional working directory for the command line.

    • state: number

      The command line's state, one of nsICommandLine.STATE_INITIAL_LAUNCH, nsICommandLine.STATE_REMOTE_AUTO, or nsICommandLine.STATE_REMOTE_EXPLICIT.

    Returns nsISupports

  • Create a command params object.

    Returns nsICommandParams

  • Create a document encoder object.

    Parameters

    • contentType: string

    Returns nsIDocumentEncoder

  • Create an HTML copy encoder object.

    Returns nsIDocumentEncoder

  • Create a loadcontext object.

    Returns nsILoadContext

  • To be called from JS only.

    Returns an object created in |vobj|'s compartment. If defineAs property on the options object is a non-null ID, the new object will be added to vobj as a property. Also, the returned new object is always automatically waived (see waiveXrays).

    Parameters

    • vobj: any
    • voptions: any

    Returns any

  • Create a persistent property object.

    Returns nsIPersistentProperties

  • Create a private loadcontext object.

    Returns nsILoadContext

  • Returns any

  • Create a spellchecker object.

    Returns nsIEditorSpellCheck

  • Dispatches a runnable to the current/main thread. If |scope| is passed, the runnable will be dispatch in the compartment of |scope|, which affects which error reporter gets called.

    Parameters

    • runnable: any
    • scope: any

    Returns void

  • evalInSandbox is designed to be called from JavaScript only.

    evalInSandbox evaluates the provided source string in the given sandbox. It returns the result of the evaluation to the caller.

    var s = new C.u.Sandbox("http://www.mozilla.org"); var res = C.u.evalInSandbox("var five = 5; 2 + five", s); var outerFive = s.five; s.seven = res; var thirtyFive = C.u.evalInSandbox("five * seven", s);

    Parameters

    • source: string
    • sandbox: any
    • version: any
    • filename: string
    • lineNo: number
    • enforceFilenameRestrictions: bool

    Returns any

  • Returns void

  • To be called from JS only.

    Instead of simply wrapping a function into another compartment, this helper function creates a native function in the target compartment and forwards the call to the original function. That call will be different than a regular JS function call in that, the |this| is left unbound, and all the non-native JS object arguments will be cloned using the structured clone algorithm. The return value is the new forwarder function, wrapped into the caller's compartment. The 3rd argument is an optional options object:

    • defineAs: the name of the property that will be set on the target scope, with the forwarder function as the value.

    Parameters

    • vfunction: any
    • vscope: any
    • voptions: any

    Returns any

  • To be called from JS only.

    If any incremental CC is in progress, finish it. For testing.

    Returns void

  • To be called from JS only.

    Force an immediate cycle collection cycle.

    Parameters

    • aListener: nsICycleCollectorListener

    Returns void

  • To be called from JS only.

    Force an immediate garbage collection cycle.

    Returns void

  • To be called from JS only.

    Force an immediate shrinking garbage collection cycle.

    Returns void

  • Gets the name of the JSClass of the object.

    if |aUnwrap| is true, all wrappers are unwrapped first. Unless you're specifically trying to detect whether the object is a proxy, this is probably what you want.

    Parameters

    • aObj: any
    • aUnwrap: bool

    Returns string

  • Get a DOM classinfo for the given classname. Only some class names are supported.

    Parameters

    • aClassName: string

    Returns nsIClassInfo

  • Returns a name for the given function or object which is useful for debugging. It will be very similar to the name displayed in call stacks. Objects which contain a single enumerable property which is a function will generate a name based on that function. Any other non-function objects will return "nonfunction".

    Parameters

    • obj: any

    Returns string

  • Returns an object containing filename and lineNumber properties describing the source location of the given function.

    Parameters

    • func: any

    Returns any

  • To be called from JS only.

    Returns the global object with which the given object is associated.

    Returns

    the corresponding global.

    Parameters

    • obj: any

      The JavaScript object whose global is to be gotten.

    Returns any

  • Gets the incument global for the execution of this function. For internal and testing use only.

    If |callback| is passed, it is invoked with the incumbent global as its sole argument. This allows the incumbent global to be measured in callback environments with no scripted frames on the stack.

    Parameters

    • callback: any

    Returns any

  • Returns any

  • Returns any

  • To be called from JS only.

    Return the longest cycle collector slice time since the last time clearMaxCCTime() was called.

    Returns number

  • Parameters

    • aLocation: string

    Returns string

  • Gets the principal of a script object, after unwrapping any cross- compartment wrappers.

    Parameters

    • obj: any

    Returns nsIPrincipal

  • Gets the URI or identifier string associated with an object's realm (the same one used by the memory reporter machinery).

    Unwraps cross-compartment wrappers first.

    The string formats and values may change at any time. Do not depend on this from addon code.

    Parameters

    • obj: any

    Returns string

  • getSandboxMetadata is designed to be called from JavaScript only.

    getSandboxMetadata retrieves the metadata associated with a sandbox object. It will return undefined if there is no metadata attached to the sandbox.

    var s = C.u.Sandbox(..., { metadata: "metadata" }); var metadata = C.u.getSandboxMetadata(s);

    Parameters

    • sandbox: any

    Returns any

  • Get the sandbox for running JS-implemented UA widgets (video controls etc.), hosted inside UA-created Shadow DOM.

    Parameters

    • principal: nsIPrincipal

    Returns any

  • Retrieve the last time, in microseconds since epoch, that a given watchdog-related event occured.

    Valid categories: "ContextStateChange" - Context switching between active and inactive states "WatchdogWakeup" - Watchdog waking up from sleeping "WatchdogHibernateStart" - Watchdog begins hibernating "WatchdogHibernateStop" - Watchdog stops hibernating

    Parameters

    • aCategory: string

    Returns number

  • To be called from JS only.

    Return a weak reference for the given JS object.

    Parameters

    • obj: any

    Returns xpcIJSWeakReference

  • When C++-Implemented code does security checks, it can generally query the subject principal (i.e. the principal of the most-recently-executed script) in order to determine the responsible party. However, when an API is implemented in JS, this doesn't work - the most-recently-executed script is always the System-Principaled API implementation. So we need another mechanism.

    Hence the notion of the "WebIDL Caller". If the current Entry Script on the Script Settings Stack represents the invocation of JS-implemented WebIDL, this API returns the principal of the caller at the time of invocation. Otherwise (i.e. outside of JS-implemented WebIDL), this function throws. If it throws, you probably shouldn't be using it.

    Returns nsIPrincipal

  • import is designed to be called from JavaScript only.

    Synchronously loads and evaluates the js file located at 'registryLocation' with a new, fully privileged global object.

    If 'targetObj' is specified and equal to null, returns the module's global object. Otherwise (if 'targetObj' is not specified, or 'targetObj' is != null) looks for a property 'EXPORTED_SYMBOLS' on the new global object. 'EXPORTED_SYMBOLS' is expected to be an array of strings identifying properties on the global object. These properties will be installed as properties on 'targetObj', or, if 'targetObj' is not specified, on the caller's global object. If 'EXPORTED_SYMBOLS' is not found, an error is thrown.

    Returns

    the module code's global object.

    The implementation maintains a hash of registryLocation->global obj. Subsequent invocations of importModule with 'registryLocation' pointing to the same file will not cause the module to be re-evaluated, but the symbols in EXPORTED_SYMBOLS will be exported into the specified target object and the global object returned as above.

    Parameters

    • aResourceURI: string
    • targetObj: any

      the object to install the exported properties on. If this parameter is a primitive value, this method throws an exception.

    Returns any

  • Imports global properties (like DOM constructors) into the scope, defining them on the caller's global. aPropertyList should be an array of property names.

    See xpc::GlobalProperties::Parse for the current list of supported properties.

    Parameters

    • aPropertyList: any

    Returns void

  • In an NS_FREE_PERMANENT_DATA build, intentionally leak a C++ object. This is needed to test leak checking.

    Returns void

  • Determines whether this object is backed by a DeadObjectProxy.

    Dead-wrapper objects hold no other objects alive (they have no outgoing reference edges) and will throw if you touch them (e.g. by reading/writing a property).

    Parameters

    • obj: any

    Returns bool

  • Returns true if the ESM is loaded into the system global previously via the ChromeUtils.importESModule method etc. Returns false otherwise.

    Parameters

    • aResourceURI: string

    Returns boolean

  • Returns true if the JSM is loaded into the system global previously via the import method above. Returns false otherwise.

    Parameters

    • aResourceURI: string

    Returns boolean

  • Returns true if the JSM is loaded into the system global previously via the import method above, or corresponding ESM is loaded. Returns false otherwise.

    Returns

    boolean, true if the js file has been loaded via import. false otherwise

    Parameters

    • aResourceURI: string

    Returns boolean

  • Check whether the given object is an opaque wrapper (PermissiveXrayOpaque).

    Parameters

    • obj: any

    Returns bool

  • To be called from JS only.

    Returns the true if the object is a (scripted) proxy. NOTE: Security wrappers are unwrapped first before the check.

    Parameters

    • vobject: any

    Returns boolean

  • Determines whether this value is a remote object proxy, such as RemoteWindowProxy or RemoteLocationProxy, for an out-of-process frame.

    Remote object proxies do not grant chrome callers the same exemptions to the same-origin-policy that in-process wrappers typically do, so this can be used to determine whether access to cross-origin proxies is safe:

    if (!Cu.isRemoteProxy(frame.contentWindow)) { frame.contentWindow.doCrossOriginThing(); }

    Parameters

    • val: any

    Returns bool

  • Check whether the given object is an XrayWrapper.

    Parameters

    • obj: any

    Returns bool

  • To be called from JS only.

    Ensures that all functions come from vobj's scope (and aren't cross compartment wrappers).

    Parameters

    • vobj: any

    Returns void

  • Return a fractional number of milliseconds from process startup, measured with a monotonic clock.

    Returns number

  • Parameters

    • obj: any

    Returns void

  • Prints the provided message to stderr.

    Parameters

    • message: string

    Returns void

  • Reads the given file and returns its contents. If called during early startup, the file will be pre-read on a background thread during profile startup so its contents will be available the next time they're read.

    The file must be a text file encoded in UTF-8. Otherwise the result is undefined.

    Parameters

    • file: nsIFile

    Returns string

  • Reads the given local file URL and returns its contents. This has the same semantics of readUTF8File. Only supports file URLs or URLs that point into one of the omnijars.

    Parameters

    • url: nsIURI

    Returns string

  • To be called from JS only. This is for Gecko internal use only, and may disappear at any moment.

    Forces a recomputation of all wrappers in and out of the compartment containing |vobj|. If |vobj| is not an object, all wrappers system-wide are recomputed.

    Parameters

    • vobj: any

    Returns void

  • reportError is designed to be called from JavaScript only.

    It will report a JS Error object to the JS console, and return. It is meant for use in exception handler blocks which want to "eat" an exception, but still want to report it to the console.

    It must be called with one param, usually an object which was caught by an exception handler. If it is not a JS error object, the parameter is converted to a string and reported as a new error.

    If called with two parameters, and the first parameter is not an object, the second parameter is used as the stack for the error report.

    Parameters

    • error: any
    • stack: any

    Returns void

  • Schedule a garbage collection cycle for a point in the future when no JS is running. Call the provided function once this has occurred.

    Parameters

    • callback: nsIScheduledGCCallback

    Returns void

  • Schedule a shrinking garbage collection cycle for a point in the future when no JS is running. Call the provided function once this has occured.

    Parameters

    • callback: nsIScheduledGCCallback

    Returns void

  • Parameters

    • zeal: number

    Returns void

  • setSandboxMetadata is designed to be called from JavaScript only.

    setSandboxMetadata sets the metadata associated with a sandbox object.

    Note that the metadata object will be copied before being used. The copy will be performed using the structured clone algorithm. Note that this algorithm does not support reflectors and it will throw if it encounters them.

    Parameters

    • sandbox: any
    • metadata: any

    Returns void

  • To be called from JS only. This is for Gecko internal use only, and may disappear at any moment.

    Enables Xray vision for same-compartment access for the compartment indicated by |vscope|. All outgoing wrappers are recomputed.

    This must not be called on chrome (system-principal) scopes.

    Parameters

    • vscope: any

    Returns void

  • Parameters

    • global: any

    Returns void

  • In a debug build, unlink any ghost windows. This is only for debugging leaks, and can cause bad things to happen if called.

    Returns void

  • Unloads the JS module at 'registryLocation'. Existing references to the module will continue to work but any subsequent import of the module will reload it and give new reference. If the JS module hasn't yet been imported then this method will do nothing.

    Parameters

    • registryLocation: string

    Returns void

  • Strip off Xray waivers on a given value. Identity op for primitives.

    Parameters

    • aVal: any

    Returns any

  • Waive Xray on a given value. Identity op for primitives.

    Parameters

    • aVal: any

    Returns any

Generated using TypeDoc