NW.js基础
What can NW.js do?
NW.js is based on Chromium and Node.js. It lets you call Node.js code and modules directly from browser and also use Web technologies in your app. Further, you can easily package a web application to a native application.
Hello World
Step 1.Create package.json:
{
"name": "helloworld", //unique name used among NW.js apps
"main": "index.html" //the first page opened by the NW.js if referenced to an HTML file
}
- Use JS File as Main : the JS file will be loaded in the background page on start and no window is opened by default. Usually you can do some initialization and open the window manually later.
Step 2.Create index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
This is the normal HTML file. You can use any web technologies supported by latest browsers, like CSS.
Step 3.Run your app:
cd /path/to/your/app
/path/to/nw .
Using NW.js APIS
All NW.js APIs are loaded in nw object globally and can be used directly in JavaScript files.
<!DOCTYPE html>
<html>
<head>
<title>Context Menu</title>
</head>
<body style="width: 100%; height: 100%;">
<p>'Right click' to show context menu.</p>
<script>
// Create an context menu, Add some items with label
var menu = new nw.Menu();
menu.append(new nw.MenuItem({
label: 'Item A',
click: function(){
alert('You have clicked at "Item A"');
}
}));
menu.append(new nw.MenuItem({ label: 'Item B' }));
menu.append(new nw.MenuItem({ type: 'separator' }));
menu.append(new nw.MenuItem({ label: 'Item C' }));
// Hooks the "contextmenu" event
document.body.addEventListener('contextmenu', function(ev) {
// Prevent showing default context menu
ev.preventDefault();
// Popup the native context menu at place you click
menu.popup(ev.x, ev.y);
return false;
}, false);
</script>
</body>
</html>
Using Node.js API
You can call node.js and modules directly from the DOM. So it enabless possibilities for writing apps with nw.js.
eg:
<!DOCTYPE html>
<html>
<head>
<title>My OS Platform</title>
</head>
<body>
<script>
// get the system platform using node.js
var os = require('os');
document.write('You are running on ', os.platform());
</script>
</body>
</html>