Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

クロスプラットフォームなアプリ作成ツール「Electron」で遊ぶ その1:導入編

electron.atom.io
Electronはクロスプラットフォームなアプリ作成ツールです。
HTMLやCSSJavaScriptといったWEBの技術を転用して、WIn、OS XLinuxのアプリを作成可能なのです。
以前、そんな趣旨の記事を書きましたが……それよか遥かにイカしてます。
shuzo-kino.hateblo.jp

実際のところ

起動確認するだけなら、nodeの環境を構築した上で公式通りにやるだけ。

$ git clone https://github.com/atom/electron-quick-start
$ cd electron-quick-start
$ npm install && npm start

全部終わると、Chromeの画面が勝手に立ち上がります。
デバッグツールが動いてますが、これは後述するJavascript内で動くよう明示されています。
f:id:shuzo_kino:20151213215823p:plain

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

*

'use strict';
const electron = require('electron');
const app = electron.app;  // Module to control application life.
const BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.

// Report crashes to our server.
electron.crashReporter.start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});