事件处理

Event

Online/Offline Detection

使用标准 HTML5 APIs 可以实现在线和离线事件的探测,就像以下例子:

main.js

var app = require('app');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});

online-status.html

<!DOCTYPE html>
<html>
<body>
<script>
var alertOnlineStatus = function() {
window.alert(navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', alertOnlineStatus);
window.addEventListener('offline', alertOnlineStatus);
alertOnlineStatus();
</script>
</body>
</html>

也会有人想要在主进程也有回应这些事件的实例。然后主进程没有 navigator 对象因此不能直接探测在线还是离线。使用 Electron 的进程间通讯工具,事件就可以在主进程被使,就像下面的例子:

main.js

var app = require('app');
var ipc = require('ipc');
var BrowserWindow = require('browser-window');
var onlineStatusWindow;
app.on('ready', function() {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
onlineStatusWindow.loadUrl('file://' + __dirname + '/online-status.html');
});
ipc.on('online-status-changed', function(event, status) {
console.log(status);
});

online-status.html

<!DOCTYPE html>
<html>
<body>
<script>
var ipc = require('ipc');
var updateOnlineStatus = function() {
ipc.send('online-status-changed', navigator.onLine ? 'online' : 'offline');
};
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();
</script>
</body>
</html>

SysProc

IPC

在主进程使用ipc模块时,ipc负责捕获从渲染进程(网页)发送的同步或者是异步消息.

发送消息

主进程也可以向渲染进程发送信息,具体可以看WebContents.send.

  • 当发送消息的时候,事件名字为'channel'.

  • 回复一个同步消息的时候,你需要使用event.returnValue

  • 回复一个异步消息的时候,使用event.sender.send(...)

下面是一个主进程和渲染进程的通信例子.

// 在主进程中.
var ipc = require('ipc');
ipc.on('asynchronous-message', function(event, arg) {
console.log(arg); // 打印 "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipc.on('synchronous-message', function(event, arg) {
console.log(arg); // 打印 "ping"
event.returnValue = 'pong';
});
// 在渲染进程(网页).
var ipc = require('ipc');
console.log(ipc.sendSync('synchronous-message', 'ping')); // 打印 "pong"
ipc.on('asynchronous-reply', function(arg) {
console.log(arg); // 打印 "pong"
});
ipc.send('asynchronous-message', 'ping');

监听消息

ipc模块有下列几种方法来监听事件.

ipc.on(channel, callback)

  • channel - 事件名称.

  • callback - 回调函数.

当事件发生的时候,会传入callback eventarg参数.

IPC 事件

传入callbackevent对象含有下列方法.

  • Event.returnValue

在同步消息中,设置这个值将会被返回.

Event.sender

返回一个可以发送消息的WebContents.

Event.sender.send(channel[.arg1][,arg2][,...])

  • channel - 事件名称.

  • arg (选用)

这个可以发送一个可带参数的异步消息回渲染进程.

Shell

shell 模块提供了集成其他桌面客户端的关联功能.

在用户默认浏览器中打开 URL 的示例:

var shell = require('shell');
shell.openExternal('https://github.com');

Methods

shell 模块包含以下函数:

shell.showItemInFolder(fullPath)

  • fullPath String

打开文件所在文件夹,一般情况下还会选中它.

shell.openItem(fullPath)

  • fullPath String

以默认打开方式打开文件.

shell.openExternal(url)

  • url String

以系统默认设置打开外部协议.(例如,mailto: somebody@somewhere.io 会打开用户默认的邮件客户端)

shell.moveItemToTrash(fullPath)

  • fullPath String

删除指定路径文件,并返回此操作的状态值(boolean 类型).

shell.beep()

播放 beep 声音.

Extension

nativefier:Wrap any web page natively

Dock Screenshot

You want to make a native wrapper for Google Maps (or any web page).

$ nativefier maps.google.com

You're done.

  • Introduction

Nativefier is a command line tool that allows you to easily create a desktop application for any web site with succinct and minimal configuration. Apps are wrapped by Electron in an OS executable (.app, .exe, etc.) for use on Windows, OSX and Linux.

I did this because I was tired of having to ⌘-tab or alt-tab to my browser and then search through the numerous open tabs when I was using Facebook Messenger or Whatsapp Web.

View the changelog here.

  • Installation

With Node.js installed,

# for use from the command line
$ npm install nativefier -g
  • Usage

Creating a native desktop app for medium.com:

$ nativefier "http://medium.com"

Nativefier will intelligently attempt to determine the app name, your OS and processor architecture, among other options. If desired, the app name or other options can be overwritten by specifying the --app-name "Medium" as part of the command line options, as such.

$ nativefier --app-name "Some Awesome App" "http://medium.com"

For Windows Users: Take note that the application menu is automatically hidden by default, you can press alt on your keyboard to access it.

  • Options

$ nativefier [options] <targetUrl> [dest]

Command line options are listed below.

Target Url

The url to point the application at.

[dest]

Specifies the destination directory to build the app to, defaults to the current working directory.

Help

-h, --help

Prints the usage information.

[app-name]

-n, --app-name <value>

The name of the application, which will affect strings in titles and the icon.

[platform]

-p, --platform <value>

Automatically determined based on the current OS. Can be overwritten by specifying either linux, win32, or darwin.

[arch]

-a, --arch <value>

Processor architecture, automatically determined based on the current OS. Can be overwritten by specifying either ia32 or x64.

[electron-version]

-e, --electron-version <value>

Electron version without the v, see https://github.com/atom/electron/releases.

[overwrite]

-o, --overwrite

Specifies if the destination directory should be overwritten.

[conceal]

-c, --conceal

Specifies if the source code within the nativefied app should be packaged into an archive, defaults to false, read more.

[icon]

-i, --icon <path>

On OSX, the icon parameter should be a path to an .icns file. iConvertIcons can be used to convert .pngs, though it can be quite cumbersome.

To retrieve the .icns file from the downloaded file, extract it first and press File > Get Info. Then select the icon in the top left corner of the info window and press ⌘-C. Open Preview and press File > New from clipboard and save the .icns file. It took me a while to figure out how to do that and question why a .icns file was not simply provided in the downloaded archive.

[badge]

-b, --badge

On OSX, it is desired for the App dock icon to show a badge on the receipt of a desktop notification.

There is no known way to intercept and set an event listener for a desktop notification triggered by the ``, the current workaround is to listen for document.title changes within the `. Typical web apps like Facebook Messenger will change thedocument.title` to "John sent a message..." on the receipt of a desktop notification, and this is what we will listen for to trigger the app badge on the dock.

However, this would cause issues when the command line argument target is set to a external page which is not a single page app, because clicking on hyperlinks and switching pages would naturally change the document.title. Hence, --badge is an optional command argument that can be set by the user if the side effect of this workaround is understood.

[counter]

--counter

Use a counter that persists even with window focus for the application badge for sites that use an "(X)" format counter in the page title (i.e. Gmail). Same limitations as the badge option (above).

[width]

--width <value>

Width of the packaged application, defaults to 1280px.

[height]

--height <value>

Height of the packaged application, defaults to 800px.

[show-menu-bar]

-m, --show-menu-bar

Specifies if the menu bar should be shown.

[user-agent]

-u, --user-agent <value>

Set the user agent to run the created app with.

[honest]

--honest

By default, nativefier uses a preset user agent string for your OS and masquerades as a regular Google Chrome browser, so that sites like WhatsApp Web will not say that the current browser is unsupported.

If this flag is passed, it will not override the user agent.

[insecure]

--insecure

Forces the packaged app to ignore certificate errors.