久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何在 Electron 中正確使用 preload.js

How to use preload.js properly in Electron(如何在 Electron 中正確使用 preload.js)
本文介紹了如何在 Electron 中正確使用 preload.js的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試在我的 renderer 進程中使用 Node 模塊(在本例中為 fs),如下所示:

I'm trying to use Node modules (in this example, fs) in my renderer processes, like this:

// main_window.js
const fs = require('fs')

function action() {
    console.log(fs)
}

注意:當我按下 main_window 中的按鈕時,會調用 action 函數.

Note: The action function gets called when I press a button in my main_window.

但這會報錯:

Uncaught ReferenceError: require is not defined
    at main_window.js:1

我可以通過將這些行添加到我的 main.js 初始化main_window時:

I can solve this issue, as suggested by this accepted answer, by adding these lines to my main.js when initializing the main_window:

// main.js
main_window = new BrowserWindow({
    width: 650,
    height: 550,
    webPreferences: {
        nodeIntegration: true
    }
})

但是,根據docs,這不是最好的做法,我應該創建一個 preload.js 文件并在那里加載這些 Node 模塊,然后在我的所有 <代碼>渲染器進程.像這樣:

But, according to the docs, this isn't the best thing to do, and I should instead, create a preload.js file and load these Node modules there and then use it in all of my renderer processes. Like this:

main.js:

main_window = new BrowserWindow({
    width: 650,
    height: 550,
    webPreferences: {
        preload: path.join(app.getAppPath(), 'preload.js')
    }
})

preload.js:

const fs = require('fs')

window.test = function() {
    console.log(fs)
}

main_window.js:

function action() {
    window.test()
}

而且它有效!

現在我的問題是,我應該在 preload.js 中編寫我的 renderer 進程的大部分代碼是否違反直覺(因為僅在 preload.js 我可以訪問 Node 模塊)然后只調用每個 renderer.js 文件中的函數(例如這里的 main_window.js)?我在這里不明白什么?

Now my question is, isn't it counter-intuitive that I should write most of the code of my renderer processes in preload.js (Because only in preload.js I have access to Node modules) and then merely call the functions in each renderer.js file (for example here, main_window.js)? What am I not understanding here?

推薦答案

編輯

正如另一位用戶所問,讓我在下面解釋我的答案.

Edit

As another user asked, let me explain my answer below.

在 Electron 中使用 preload.js 的正確方法是在您的應用可能需要 require 的任何模塊周圍公開列入白名單的包裝器.

The proper way to use the preload.js in Electron is to expose whitelisted wrappers around any module your app may need to require.

安全方面,在 preload.js 中暴露 require 或通過 require 調用檢索到的任何內容都是危險的(請參閱 我在這里的評論了解更多原因).如果您的應用加載遠程內容(很多人都會這樣做),則尤其如此.

Security-wise, it's dangerous to expose require, or anything you retrieve through the require call in your preload.js (see my comment here for more explanation why). This is especially true if your app loads remote content, which many do.

為了正確地做事,您需要在 <代碼>BrowserWindow 如下所述.設置這些選項會強制您的電子應用程序通過 IPC(進程間通信)進行通信,并將兩個環境相互隔離.像這樣設置您的應用程序可以讓您驗證后端中可能是 require 的任何模塊,而客戶端不會對其進行篡改.

In order to do things right, you need to enable a lot of options on your BrowserWindow as I detail below. Setting these options forces your electron app to communicate via IPC (inter-process communication) and isolates the two environments from each other. Setting up your app like this allows you to validate anything that may be a require'd module in your backend, which is free from the client tampering with it.

您將在下面找到一個簡短示例,說明我所說的內容以及它在您的應用中的外觀.如果你剛開始,我可能會建議使用 secure-electron-template(我是其中的作者)在構建電子應用程序時從一開始就包含了所有這些安全最佳實踐.

Below, you will find a brief example of what I speak about and how it can look in your app. If you are starting fresh, I might suggest using secure-electron-template (which I am the author of) that has all of these security best-practices baked in from the get go when building an electron app.

這個頁面也有很好的信息關于使用 preload.js 制作安全應用時所需的架構.

This page also has good information on the architecture that's required when using the preload.js to make secure apps.

ma??in.js

const {
  app,
  BrowserWindow,
  ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

async function createWindow() {

  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // is default value after Electron v5
      contextIsolation: true, // protect against prototype pollution
      enableRemoteModule: false, // turn off remote
      preload: path.join(__dirname, "preload.js") // use a preload script
    }
  });

  // Load app
  win.loadFile(path.join(__dirname, "dist/index.html"));

  // rest of code..
}

app.on("ready", createWindow);

ipcMain.on("toMain", (event, args) => {
  fs.readFile("path/to/file", (error, data) => {
    // Do something with file contents

    // Send result back to renderer process
    win.webContents.send("fromMain", responseObj);
  });
});

preload.js

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

index.html

<!doctype html>
<html lang="en-US">
<head>
    <meta charset="utf-8"/>
    <title>Title</title>
</head>
<body>
    <script>
        window.api.receive("fromMain", (data) => {
            console.log(`Received ${data} from main process`);
        });
        window.api.send("toMain", "some data");
    </script>
</body>
</html>

這篇關于如何在 Electron 中正確使用 preload.js的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

discord.js v12: How do I await for messages in a DM channel?(discord.js v12:我如何等待 DM 頻道中的消息?)
how to make my bot mention the person who gave that bot command(如何讓我的機器人提及發出該機器人命令的人)
How to fix Must use import to load ES Module discord.js(如何修復必須使用導入來加載 ES 模塊 discord.js)
How to list all members from a specific server?(如何列出來自特定服務器的所有成員?)
Discord bot: Fix ‘FFMPEG not found’(Discord bot:修復“找不到 FFMPEG)
Welcome message when joining discord Server using discord.js(使用 discord.js 加入 discord 服務器時的歡迎消息)
主站蜘蛛池模板: 中国一级特黄毛片大片 | 亚洲91精品 | 久久精品播放 | 国产精品视频久久 | 国产精品亚洲片在线播放 | 粉嫩一区二区三区四区公司1 | 中文字幕在线第二页 | 欧美在线一区二区三区 | 成人一区二区三区 | 精品欧美一区二区三区 | 国产欧美一区二区三区免费 | 欧美久久天堂 | 亚洲精品一区二区三区中文字幕 | 这里只有精品999 | 久久综合九色综合欧美狠狠 | 欧美一极视频 | 狠狠草视频 | 国产精品久久久久久久久久久久久久 | 婷婷99 | 日韩www| 日韩国产中文字幕 | 一区二区三区四区不卡 | 成人激情视频网 | 在线观看国产 | 欧美一区在线视频 | 色屁屁在线观看 | 日韩视频免费 | 在线免费av电影 | 国产激情在线观看 | 中文字幕亚洲欧美日韩在线不卡 | 日本视频免费观看 | 黄色在线观看网址 | 亚洲第一av | 国产激情福利 | 国产精品伦一区二区三级视频 | 新超碰97| 成人一级视频在线观看 | 欧美精品一区二区免费 | 羞羞视频一区二区 | 全免费a级毛片免费看视频免费下 | 国产午夜精品一区二区三区四区 |