Reference 'this' is undefined in Electron

2019-08-29 08:47发布

问题:

My Electron app loads index.html after app.on("ready", but this in the script tag doesn't point to the Window object as expected. Any idea why?

If I console.log(Window), the object does exist and prints this

global {frames: global, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

main.js ... Loads index.html

app.on("ready", function () {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 2000,
    webPreferences: {
      nodeIntegration: true
    },
  },

  mainWindow.loadURL("file://" + __dirname + "/index.html");
}

index.html ... 'this' is undefined

<script src="elm.js"></script>
<script>
    console.log(this) // This returns 'undefined'

    var app = Elm.Main.init({
        node: document.getElementById('elm')
    });
</script>

elm.js .... passes undefined 'this' to the function causing an error

(function(scope){
'use strict';

 --- omitted ----

var author$project$Main$main = elm$browser$Browser$sandbox(
    {init: author$project$Main$init, update: author$project$Main$update, view: author$project$Main$view});
_Platform_export({'Main':{'init':author$project$Main$main(
    elm$json$Json$Decode$succeed(_Utils_Tuple0))(0)}});}(this));