簡體   English   中英

電子初學者,如何從菜單讀取文件到 html?

[英]Electron beginner, how to read file from menu to html?

我創建了一個簡單的電子項目,創建了一個菜單,用於打開文件,一切都很好,直到我從文件中獲取數據。 我發現沒有document$對象,如何將數據傳遞給 DOM,例如p textContext?

dialog.showOpenDialog({properties: ['openFile']}, (filePath) => {
        // read the file
        fs.readFile(filePath[0], (err, data) => {
            if (err) {
                // do something
            } else {
                // this not work
                document.getElementsByTagName("p")[0].textContent = data.toString();
            }
        })
    });
}

您無權訪問主進程中的document (我想您在其中擁有此代碼)。 您必須通過使用 IPC、HTML 代碼執行甚至全局變量在您的進程之間進行通信。 (你可以在網上找到很多關於它的文章)詳細信息請參閱electron's architecture

處理這種情況的一個例子可能是

主文件

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

app.once('ready', () => {
  let win = new BrowserWindow()
  win.loadURL(path.join(__dirname, 'index.html'))
  win.setMenu(Menu.buildFromTemplate([
    {
      label: 'Open File',
      click (menuItem, browserWindow, event) {
        dialog.showOpenDialog({
          properties: ['openFile']
        }, (filePath) => {
          fs.readFile(filePath[0], (err, data) => {
            if (!err) {
              browserWindow.webContents.send('print-file', data.toString())
            }
        })
        })
      }
    }
  ]))
})

索引.html

<html>
  <body>
    <script>
      const { ipcRenderer } = require('electron')
      ipcRenderer.on('print-file', (event, datastr) => {
        document.getElementsByTagName("p")[0].textContent = datastr
      })
    </script>
    <p></p>
  </body>
</html>

我現在沒有可以測試的環境,但我認為您編寫的showOpenDialog不正確。 如果您查看手冊頁,第一個參數是可選的瀏覽器窗口對象。 看起來您沒有使用,所以您的代碼應該是:

dialog.showOpenDialog(null, {properties: ['openFile']}, (filePath) => {
        // read the file
        fs.readFile(filePath[0], (err, data) => {
            if (err) {
                // do something
                console.log('ERROR: ' + data);
            } else {
                // this not work
                console.log('PASS: ' + data);
                document.getElementsByTagName("p")[0].textContent = data.toString();
            }
        })
    });
}

當參數(參數)是可選的時,您仍然需要發送一些內容。因為您不想使用它,所以我發送了null因此showOpenDialog函數知道您不會使用它。 我還添加了一些console.log()以便您可以在嘗試使用data之前測試您的結果。

主要.js:

 Menu.setApplicationMenu(Menu.buildFromTemplate([
      {
        label: '&File',
        submenu: [
          {
            label: 'Open',
            accelerator: 'CmdOrCtrl+O',
            click() {
              showOpen()
            }
          },
          { type: 'separator' },
          {
            role: 'quit',
            accelerator: 'CmdOrCtrl+Q'
          }
        ]
      }])
    
      function showOpen() {
        dialog.showOpenDialog({
          properties: ['openFile']
        }).then(result => {
          console.log(result.canceled)  // Optional
          console.log(result.filePaths) // Optional
          
          // Read first file of list (or process an array of files)
          readFile(result.filePaths[0]) 
        }).catch(err => {
          console.log(err)
        })
      }
    
      function readFile(filepath) {
        fs.readFile(filepath, 'utf-8', (err, data) => {
          if(err){
            alert("An error ocurred reading the file :" + err.message)
            return
          }
          console.log(JSON.parse(data)) // For JSON file only
        })
      }

代替console.log(JSON.parse(data)) ,您處理文件,然后使用例如IPC將其發送到瀏覽器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM