去年基于NW.js 0.12.3做過一個項目,當時對于NW中的contexts的理解比較模糊。今天在twiiter上看到發(fā)布新的版本,重新又打開了nwjs.io網(wǎng)站的文檔部分,落地頁面是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的文檔,很多概念有了更新的理解。對網(wǎng)站文檔的印象也比之前大為改善。_