vm.createContext([contextObject[, options]])


  • contextObject <Object>
  • options <Object>
    • name <string> 新创建的上下文的人类可读名称。 默认值: 'VM Context i',其中 i 是创建的上下文的升序数字索引。
    • origin <string> 对应于新创建用于显示目的的上下文的原点。 原点应格式化为类似一个 URL,但只包含协议,主机和端口(如果需要),例如 URL 对象的 url.origin 属性的值。 最值得注意的是,此字符串应省略尾部斜杠,因为它表示路径。 默认值: ''
    • codeGeneration <Object>
      • strings <boolean> 如果设置为 false,则对 eval 或函数构造函数(FunctionGeneratorFunction 等)的任何调用都将抛出 EvalError默认值: true
      • wasm <boolean> 如果设置为 false,则任何编译 WebAssembly 模块的尝试都将抛出 WebAssembly.CompileError默认值: true
    • microtaskMode <string> If set to afterEvaluate, microtasks (tasks scheduled through Promises and async functions) will be run immediately after a script has run through script.runInContext(). They are included in the timeout and breakOnSigint scopes in that case.
  • 返回: <Object> 上下文隔离化的沙盒。

给定一个 contextObject 对象, vm.createContext()设置此沙盒,从而让它具备在 vm.runInContext() 或者 script.runInContext() 中被使用的能力。 在此类脚本中, contextObject 将会是全局对象,保留其所有现有属性,但还具有任何标准的全局对象具有的内置对象和函数。 在 vm 模块运行的脚本之外,全局变量将会保持不变。

const vm = require('vm');

global.globalVar = 3;

const context = { globalVar: 1 };
vm.createContext(context);

vm.runInContext('globalVar *= 2;', context);

console.log(context);
// 打印: { globalVar: 2 }

console.log(global.globalVar);
// 打印: 3

如果未提供 contextObject(或者传入undefined),那么会返回一个全新的空的上下文隔离化对象。

vm.createContext() 主要是用于创建一个能运行多个脚本的上下文。 比如说,在模拟一个网页浏览器时,此方法可以被用于创建一个单独的上下文来代表一个窗口的全局对象,然后所有的 <script> 标签都可以在这个上下文中运行。

通过 Inspector API 可以看到提供的上下文的 nameorigin

  • contextObject <Object>
  • options <Object>
    • name <string> Human-readable name of the newly created context. Default: 'VM Context i', where i is an ascending numerical index of the created context.
    • origin <string> Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the url.origin property of a URL object. Most notably, this string should omit the trailing slash, as that denotes a path. Default: ''.
    • codeGeneration <Object>
      • strings <boolean> If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) will throw an EvalError. Default: true.
      • wasm <boolean> If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. Default: true.
    • microtaskMode <string> If set to afterEvaluate, microtasks (tasks scheduled through Promises and async functions) will be run immediately after a script has run through script.runInContext(). They are included in the timeout and breakOnSigint scopes in that case.
  • Returns: <Object> contextified object.

If given a contextObject, the vm.createContext() method will prepare that object so that it can be used in calls to vm.runInContext() or script.runInContext(). Inside such scripts, the contextObject will be the global object, retaining all of its existing properties but also having the built-in objects and functions any standard global object has. Outside of scripts run by the vm module, global variables will remain unchanged.

const vm = require('vm');

global.globalVar = 3;

const context = { globalVar: 1 };
vm.createContext(context);

vm.runInContext('globalVar *= 2;', context);

console.log(context);
// Prints: { globalVar: 2 }

console.log(global.globalVar);
// Prints: 3

If contextObject is omitted (or passed explicitly as undefined), a new, empty contextified object will be returned.

The vm.createContext() method is primarily useful for creating a single context that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single context representing a window's global object, then run all <script> tags together within that context.

The provided name and origin of the context are made visible through the Inspector API.