Rahul
Rahul

Reputation: 1256

`document` is not defined Electron

I'm trying to read JSON from a file using the fs module, and display that in a div with id list in an Electron app. My code in index.js looks like this:

dialog.showOpenDialog((filenames) => {
  if (!filenames) return;
      
  fs.readFile(filenames[0], (err, data) => {
    if (err) {
      alert('Could not read file.\n\nDetails:\n' + err.message);
      return;
    }

    let json = JSON.parse(data).en;
    for (let i = 0; i < json.length; ++i) {
      let html = "<div class='entry'><b>";
      // Add more to html variable from json data
          
      $('list').html(html); 
    }
  });
});

I get an error saying:

Uncaught Exception:

Error: jQuery requires a window with a document

How do I modify the DOM from the JS, and why do I get this error?

Upvotes: 7

Views: 22405

Answers (2)

pergy
pergy

Reputation: 5521

You can use executeJavascript method of your BrowserWindow's webContents to execute code directly in Renderer process.

const { app, BrowserWindow} = require('electron')
const path = require('path')
const fs = require('fs')

app.once('ready', () => {
  var mainWindow = new BrowserWindow()
  mainWindow.loadURL(path.join(__dirname, 'index.html'))

  fs.readFile(path.join(__dirname, 'test.json'), 'utf8', (err, data) => {
    if (err) {
      alert('Could not read file.\n\nDetails:\n' + err.message)
      return
    }
    let json = JSON.parse(data)
    for (let i in json) {
      mainWindow.webContents.executeJavaScript(`
        document.getElementById("list").innerHTML += '<br> ${i}: ${json[i]}'
      `)
      // can be replaced with
      // $('#list').append('<br> ${i}: ${json[i]}')
      // if html have jquery support
    }
  })
})

For using jquery in electron you should install jquery module and refer it in your HTML

<script>window.$ = window.jQuery = require('jquery');</script>

Instructions in detail can be found here

Upvotes: 8

fxlacroix
fxlacroix

Reputation: 567

you can try this

window.$ = require('jquery')(window);

it corrects this error for me

Upvotes: -3

Related Questions