去年基于NW.js 0.12.3做过一个项目,当时对于NW中的contexts的理解比较模糊。今天在twiiter上看到发布新的版本,重新又打开了nwjs.io网站的文档部分,落地页面是NW中的contexts的介绍。这里做一整理,加深理解。
首先理解Contexts的概念,概念是对一个事物最准确的诠释和定义。
Contexts in NW.js
NW.js is based on the architecture of Chrome Apps. Thus an invisible background page is loaded automatically at start. And when a new window is created, a JavaScript context is created as well.
In NW.js, Node.js modules can be loaded in the context running in background page, which is the default behavior. Also they can be loaded within the context of each window or frame when running as Mixed Context Mode. Continue to read following sections to see the differences between Separate Context Mode and Mixed Context Mode.
Separate Context Mode
Besides the contexts created by browsers, NW.js introduced additional Node context for running Node modules in the background page by default. So NW.js has two types of JavaScript contexts: Browser Context and Node Context.
ccess Browser and NW.js API in Node Context
In Node context, there are no browser side or NW.js APIs, such as alert()
or document.*
or nw.Clipboard
etc. To access browser APIs, you have to pass the corresponding objects, such as window
object, to functions in Node context.
See following example for how to achieve this.
Following script are running in Node context (myscript.js):
// `el` should be passed from browser context
exports.setText = function(el) {
el.innerHTML = 'hello';
};
In the browser side (index.html):
<div id="el"></div>
<script>
var myscript = require('./myscript');
// pass the `el` element to the Node function
myscript.setText(document.getElementbyId('el'));
// you will see "hello" in the element
</script>
window
in Node Context
There is a window
object in Node context pointing to the DOM window object of the background page.
Mixed Context Mode
Mixed context is introduced in NW.js 0.13. When running NW.js with --mixed-context
CLI option, a new Node context is created at the time of each browser context creation and running in a same context as browser context, a.k.a. the Mixed context.
Comparing with Separate Context
The advantage of Separate Context Mode is that you will not encounter many type checking issue as below.
The cons is that in Mixed Context Mode, you can’t share variable easily as before. To share variables among contexts, you should put variables in a common context that can be accessed from the contexts you want to share with. Or you can use window.postMessage()
API to send and receive messages between contexts.
再次回看nwjs的文档,很多概念有了更新的理解。对网站文档的印象也比之前大为改善。_
网友评论