Electron讀取本地文件並顯示


Electron讀取本地文件並顯示,也就是暴露一個讀取本地特定文件內容的接口給渲染進程調用。

主要參考:https://stackoverflow.com/questions/44391448/electron-require-is-not-defined

基於官方的快速教程示例代碼進行修改,原始代碼如下:

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
main.js
// preload.js

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const replaceText = (selector, text) => {
    const element = document.getElementById(selector)
    if (element) element.innerText = text
  }

  for (const dependency of ['chrome', 'node', 'electron']) {
    replaceText(`${dependency}-version`, process.versions[dependency])
  }
})
preload.js
<!--index.html-->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <!-- You can also require other files to run in this process -->
    <script src="./renderer.js"></script>
  </body>
</html>
index.html

一、似乎不安全的辦法

把nodeIntegration設置為true,contextIsolation設置為false:

  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
 nodeIntegration: true, contextIsolation: false,
    }
  })

這樣子就可以直接在渲染器處運行Node.js代碼:

// renderer.js

let fs = require("fs");

fs.readFile('local_file.txt', (err, data) => {
    if (err) return console.error(err);
    console.log(data.toString());
});

但是這樣造成的結果是,別人有可能通過Node.js運行環境隨便操控本地操作系統的文件,或者造成其它風險:

二、直接寫在preload.js中

為啥一定要寫在renderer.js里呢?直接寫在preload.js里就好了。(新手的疑惑:之所以區分preload.js和renderer.js是一種類似於“前后端分離”的思想嗎?有什么東西不能直接寫在preload.js ,非得寫在renderer.js里的呢?有說法是“通過預加載把用到的api暴露到全局,這樣主進程和渲染進程都能用”;有說法是“preload.js是為了把一些原屬於electron的代碼 通過windows["xxxxx"] 提供給前台js調用的”)

在index.html中添加一個按鈕,每按一次從本地讀取一次文件:

<button id="btn1">按鈕1</button>

修改preload.js:

// preload.js
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
省略號
  let readAndDisplay = () => {
    let fs = require("fs");
    fs.readFile('local_file.txt', (err, data) => {
      if (err) return console.error(err);
      console.log(data.toString());
      let myNode = document.createTextNode(data.toString());
      document.body.insertBefore(myNode, document.body.firstChild);
    });
  }

  document.querySelector('#btn1').addEventListener("click", event => {
    readAndDisplay();
  })
省略號
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM