`document`未定义Electron

时间:2017-06-09 10:24:31

标签: javascript jquery electron

我正在尝试使用fs模块从文件中读取JSON,并在Electron应用中的div中显示ID list。我在index.js中的代码如下所示:

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); 
    }
  });
});

我收到错误说:

  

未捕获的例外:

     

错误:jQuery需要一个带文档的窗口

如何从JS修改DOM,为什么会出现此错误?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-1)

你可以试试这个

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

它为我纠正了这个错误