Bye Bye Moore

猫マンション建築の野望を胸に零細事業主として資本主義の荒波に漕ぎ出したアラサー男の技術メモ

クロスプラットフォームなアプリ作成ツール「Electron」で遊ぶ その3:自前のJSファイルはいつ読まれるか

考えてみれば当たり前なのですが……
起動の順番としては
1. main.js
2. index.html
3. index.htmlで読み出されたjs
という順で処理されます。
というわけで……addEventListner等々、自前のスクリプトはmain.jsに書いても無駄です。

実際のところ

main.js

'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: 640, height: 480});
    mainWindow.loadURL(`file://${__dirname}/index.html`);
		       
  // 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;
  });
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <script src="./app.js"></script>
    <webview id="foo" src="https://duckduckgo.com/" style="display:inline-block; width:320px; height:240px">...loading</webview>
<p>str</p>
    <form>
      <input type="button" id="btn1" value="CLICKHERE">
      <input type="button" value="<=" onClick="webview.goBack();">
    </form>
  </body>
</html>

app.js

onload = function(){
   alert("done");
};

onload = function() {
    var btn1 = document.getElementById("btn1");
    btn1.onclick = function(){
	document.bgColor='#000000';
    }
    
    var webview = document.getElementById("foo");
    var indicator = document.querySelector(".indicator");
    
    var loadstart = function() {
	indicator.innerText = "loading...";
    }
    
    var loadstop = function() {
	indicator.innerText = "";
    }
    
    webview.addEventListener("did-start-loading", loadstart);
    webview.addEventListener("did-stop-loading", loadstop);
};

参考もと

electron.atom.io