Document is not defined error in Electron


#1

Hello there!

I started working on Electron and facing a problem, would be grateful if anyone can help

I was trying to:

Open a file and Display its contents.

But I face the Document is not defined Error.

This is the project structure:

 text_editor
 ---->main_process
      ---->menus
          ---->application_menu.js
 ---->renderer_process
       ---->open_file.js
 ---->index.html
 ---->main.js
 ---->package.json

this is application_menu.js:

  const { app, BrowserWindow, Menu } = require('electron')
const electron = require('electron')
const fs = require('fs')
const ipc = require('electron').ipcMain
const open_file = require('../../renderer_process/open_file')

const template = [{
    label: 'File',
    submenu: [{
        label: 'Open File..',
        click() {open_file.open()}
    }, ]
}]

electron.app.on('ready', () => {
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
})

and this is open_file.js:

    const ipc = require('electron').ipcRenderer
const electron = require('electron')
const fs = require('fs')


let open_file = {
    open() {
        console.log("reached here again");
        electron.dialog.showOpenDialog(function(fileNames) {
                if (fileNames === undefined)
                    return;
                else {
                    var fileName = fileNames[0];

                    fs.readFile(fileName, 'utf-8', function(err, data) {
                            document.getElementById("editor").value = data;
                        })
                    }
            })
        }
    }
        module.exports = open_file

and index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Foo Text Editor</title>
  </head>
  <body>
    <h1>Foo Text Editor</h1>
    <p>Welcome here</p>
    <p id="editor"></p>
		<script>
			require('./renderer_process/open_file')
		</script>
  </body>
</html>

When Open in the Menu Bar is clicked, it shows the dialog to select file, but when the file is opened it raises the document is not defined error.