Skip to content

Instantly share code, notes, and snippets.

@TaijaQ
Last active March 8, 2016 22:58
Show Gist options
  • Save TaijaQ/3c15b08e8c5bdc7168ab to your computer and use it in GitHub Desktop.
Save TaijaQ/3c15b08e8c5bdc7168ab to your computer and use it in GitHub Desktop.
Node Webkit basics
<html>
<body>
<script>
// get the system platform using node.js
var os = require('os')
document.write('Our computer is: ', os.platform())
</script>
</body>
</html>
// Load native UI library
var gui = require('nw.gui');
// We can not create a clipboard, we have to receive the system clipboard
var clipboard = gui.Clipboard.get();
// Read from clipboard
var text = clipboard.get('text');
console.log(text);
// Or write something
clipboard.set('I love node-webkit :)', 'text');
// And clear it!
clipboard.clear();
<html>
<body>
<style>
#holder { border: 10px dashed #ccc; width: 300px; height: 300px; margin: 20px auto;}
#holder.hover { border: 10px dashed #333; }
</style>
<div id="holder"></div>
<script>
// prevent default behavior from changing page on dropped file
window.ondragover = function(e) { e.preventDefault(); return false };
window.ondrop = function(e) { e.preventDefault(); return false };
var holder = document.getElementById('holder');
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragleave = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
e.preventDefault();
for (var i = 0; i < e.dataTransfer.files.length; ++i) {
console.log(e.dataTransfer.files[i].path);
}
return false;
};
</script>
</body>
</html>
holder.ondrop = function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
// Load native UI library.
var gui = require('nw.gui');
// Open URL with default browser.
gui.Shell.openExternal('https://github.com/rogerwang/node-webkit');
// Open a text file with default text editor.
gui.Shell.openItem('test.txt');
// Open a file in file explorer.
gui.Shell.showItemInFolder('test.txt');
<script>
function chooseFile(name) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
console.log(this.value);
}, false);
chooser.click();
}
chooseFile('#fileDialog');
</script>
var files = $('#fileDialog')[0].files;
for (var i = 0; i < files.length; ++i)
console.log(files[i].name);
<!DOCTYPE html>
<html>
<head>
<title>webRTC Test</title>
</head>
<body onload="init();" style="background-color:#ababab;" >
<div style="width:352px; height:625px; margin:0 auto; background-color:#fff;" >
<div>
<video id="camFeed" width="320" height="240" autoplay>
</video>
</div>
<div>
<canvas id="photo" width="320" height="240">
</canvas>
</div>
<div style="margin:0 auto; width:82px;">
<input type="button" value="Take Photo" onclick="takePhoto();">
</div>
</div>
<script>
function init()
{
if(navigator.webkitGetUserMedia)
{
navigator.webkitGetUserMedia({video:true}, onSuccess, onFail);
}
else
{
alert('webRTC not available');
}
}
function onSuccess(stream)
{
document.getElementById('camFeed').src = webkitURL.createObjectURL(stream);
}
function onFail()
{
alert('could not connect stream');
}
function takePhoto()
{
var c = document.getElementById('photo');
var v = document.getElementById('camFeed');
c.getContext('2d').drawImage(v, 0, 0, 320, 240);
}
</script>
</body>
</html>
<html>
<head>
<title> Menu </title>
</head>
<body>
<script>
// Load native UI library
var gui = require('nw.gui');
// Create an empty menu
var menu = new gui.Menu();
// Add some items with label
menu.append(new gui.MenuItem({ label: 'Item A' }));
menu.append(new gui.MenuItem({ label: 'Item B' }));
menu.append(new gui.MenuItem({ type: 'separator' }));
menu.append(new gui.MenuItem({ label: 'Item C' }));
// Remove one item
menu.removeAt(1);
// Iterate menu's items
for (var i = 0; i < menu.items.length; ++i) {
console.log(menu.items[i]);
}
// Add a item and bind a callback to item
menu.append(new gui.MenuItem({
label: 'Click Me',
click: function() {
// Create element in html body
var element = document.createElement('div');
element.appendChild(document.createTextNode('Clicked OK'));
document.body.appendChild(element);
}
}));
// Popup as context menu
document.body.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
// Popup at place you click
menu.popup(ev.x, ev.y);
return false;
}, false);
// Get the current window
var win = gui.Window.get();
// Create a menubar for window menu
var menubar = new gui.Menu({ type: 'menubar' });
// Create a menuitem
var sub1 = new gui.Menu();
sub1.append(new gui.MenuItem({
label: 'Test1',
click: function() {
var element = document.createElement('div');
element.appendChild(document.createTextNode('Test 1'));
document.body.appendChild(element);
}
}));
// You can have submenu!
menubar.append(new gui.MenuItem({ label: 'Sub1', submenu: sub1}));
//assign the menubar to window menu
win.menu = menubar;
// add a click event to an existing menuItem
menu.items[0].click = function() {
console.log("CLICK");
};
</script>
</body>
</html>
var options = {
icon: "http://yourimage.jpg",
body: "Here is the notification text"
};
var notification = new Notification("Notification Title",options);
notification.onclick = function () {
document.getElementById("output").innerHTML += "Notification clicked";
}
notification.onshow = function () {
// play sound on show
myAud=document.getElementById("audio1");
myAud.play();
// auto close after 1 second
setTimeout(function() {notification.close();}, 1000);
}
var NW = require('nw.gui');
// Extend application menu for Mac OS
if (process.platform == "darwin") {
var menu = new NW.Menu({type: "menubar"});
menu.createMacBuiltin && menu.createMacBuiltin(window.document.title);
NW.Window.get().menu = menu;
}
var $ = function (selector) {
return document.querySelector(selector);
}
document.addEventListener('DOMContentLoaded', function() {
$('#simple-coffee').addEventListener('click', function (event) {
showNotification("./icons/coffee.png", "Your coffee", 'is ready...')
});
$('#simple-camera').addEventListener('click', function (event) {
var notif = showNotification("./icons/camera.png", "Camera", 'example notification');
setTimeout(function () {
notif.close();
}, 1200);
});
$('#simple-car').addEventListener('click', function (event) {
showNotification('./icons/car.png', "Taxi is arrived", 'hurry up');
});
$('#node-notifier-coffee').addEventListener('click', function (event) {
showNativeNotification("./icons/coffee.png", "Your coffee", 'is ready...', 'default')
});
$('#node-notifier-camera').addEventListener('click', function (event) {
showNativeNotification("./icons/camera.png", "Camera", 'example notification', 'Glass');
});
$('#node-notifier-car').addEventListener('click', function (event) {
showNativeNotification(false, "Taxi is arrived", 'hurry up', false, './icons/car.png');
});
$('#nw-notify-coffee').addEventListener('click', function (event) {
showHtmlNotification("./icons/coffee.png", "Your coffee", 'is ready...');
});
$('#nw-notify-camera').addEventListener('click', function (event) {
showHtmlNotification("./icons/camera.png", "Camera", 'example notification', function (event) {
setTimeout(function () {
console.log("closing notification on timeout", event)
event.closeNotification();
}, 1200);
});
});
$('#nw-notify-car').addEventListener('click', function (event) {
showHtmlNotification('./icons/car.png', "Taxi is arrived", 'hurry up');
});
// bring window to front when open via terminal
NW.Window.get().focus();
// for nw-notify frameless windows
NW.Window.get().on('close', function() {
NW.App.quit();
});
});
var writeLog = function (msg) {
var logElement = $("#output");
logElement.innerHTML += msg + "<br>";
logElement.scrollTop = logElement.scrollHeight;
};
// NW.JS Notification
var showNotification = function (icon, title, body) {
if (icon && icon.match(/^\./)) {
icon = icon.replace('.', 'file://' + process.cwd());
}
var notification = new Notification(title, {icon: icon, body: body});
notification.onclick = function () {
writeLog("Notification clicked");
};
notification.onclose = function () {
writeLog("Notification closed");
NW.Window.get().focus();
};
notification.onshow = function () {
writeLog("-----<br>" + title);
};
return notification;
}
// NODE-NOTIFIER
var showNativeNotification = function (icon, title, message, sound, image) {
var notifier;
try {
notifier = require('node-notifier');
} catch (error) {
console.error(error);
if (error.message == "Cannot find module 'node-notifier'") {
window.alert("Can not load module 'node-notifier'.\nPlease run 'npm install'");
}
return false;
}
var path = require('path');
icon = icon ? path.join(process.cwd(), icon) : undefined;
image = image ? path.join(process.cwd(), image) : undefined;
notifier.notify({
title: title,
message: message,
icon: icon,
appIcon: icon,
contentImage: image,
sound: sound,
wait: false,
sender: 'org.nwjs.sample.notifications'
}, function (err, response) {
if (response == "Activate\n") {
writeLog("node-notifier: notification clicked");
NW.Window.get().focus();
}
});
writeLog("-----<br>node-notifier: " + title);
};
// NW-NOTIFY
var showHtmlNotification = function (icon, title, body, callback) {
var notifier;
try {
notifier = require('nw-notify');
} catch (error) {
console.error(error);
if (error.message == "Cannot find module 'nw-notify'") {
window.alert("Can not load module 'nw-notify'.\nPlease run 'npm install'");
return false;
}
}
// give it nice look
notifier.setConfig({
defaultStyleContainer: {
border: '1px solid #9D9D9D',
borderRadius: '6px',
backgroundColor: 'rgba(245, 245, 245, 0.94)',
fontFamily: 'Helvetica Neue',
boxShadow: '0px 0px 11px rgba(0, 0, 0, 0.4)',
fontSize: 12,
position: 'relative',
lineHeight: '17px',
padding: '8px 12px 8px 14px'
}
});
if (icon) icon = notifier.getAppPath() + icon;
notifier.notify({
title: title,
text: body,
iconPath: icon,
onShowFunc: function (event) {
if (callback) callback(event);
writeLog("-----<br>nw-notify: " + title);
},
onClickFunc: function (event) {
writeLog("nw-notify notification clicked");
},
onCloseFunc: function (event) {
if (event.event == 'close') {
writeLog("nw-notify notification closed ");
}
}
});
};
// Load native UI library
var gui = require('nw.gui'); //or global.window.nwDispatcher.requireNwGui() (see https://github.com/rogerwang/node-webkit/issues/707)
// Get the current window
var win = gui.Window.get();
// Listen to the minimize event
win.on('minimize', function() {
console.log('Window is minimized');
});
// Minimize the window
win.minimize();
// Unlisten the minimize event
win.removeAllListeners('minimize');
// Create a new window and get it
var new_win = gui.Window.open('https://github.com');
// And listen to new window's focus event
new_win.on('focus', function() {
console.log('New window is focused');
});
// Load native UI library.
var gui = require('nw.gui');
var option = {
key : "Ctrl+Shift+A",
active : function() {
console.log("Global desktop keyboard shortcut: " + this.key + " active.");
},
failed : function(msg) {
// :(, fail to register the |key| or couldn't parse the |key|.
console.log(msg);
}
};
// Create a shortcut with |option|.
var shortcut = new gui.Shortcut(option);
// Register global desktop shortcut, which can work without focus.
gui.App.registerGlobalHotKey(shortcut);
// If register |shortcut| successfully and user struck "Ctrl+Shift+A", |shortcut|
// will get an "active" event.
// You can also add listener to shortcut's active and failed event.
shortcut.on('active', function() {
console.log("Global desktop keyboard shortcut: " + this.key + " active.");
});
// Only add setZeroTimeout to the window object, and hide
// everything else in a closure.
(function() {
var timeouts = [];
var messageName = "zero-timeout-message";
// Like setTimeout, but only takes a function argument.
// There's no time argument (always 0) and no function's arguments
// (you have to use a closure if such arguments are necessary).
function setZeroTimeout(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
}
function handleMessage(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
}
window.addEventListener("message", handleMessage, true);
// Add the one thing we want added to the window object.
window.setZeroTimeout = setZeroTimeout;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment