`document` is not defined Electron

北城以北 提交于 2021-01-27 18:25:20

问题


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?


回答1:


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




回答2:


you can try this

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

it corrects this error for me



来源:https://stackoverflow.com/questions/44455356/document-is-not-defined-electron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!