簡體   English   中英

使用 Electron 和 ContextIsolation 打開文件/文件夾

[英]Opening files/folders using Electron and ContextIsolation

我一直在嘗試構建一個用於文件管理和不同工作內容的應用程序。 其中一項功能是在 windows 文件資源管理器中打開鏈接,但我做不到。 這些是從應用程序代碼的 rest 中分離出來的文件:

索引.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <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 from Electron renderer!</title>
  </head>
  <body>
    <h1>Hello from Electron renderer!</h1>
    <p>👋</p>
    <p id="info"></p>
    <div>
        <button id="open-file-manager">View Demo</button>
    </div>
  </body>
  <script src="./renderer.js"></script>
</html>

主要

const { app, BrowserWindow } = require('electron');
const path = require('path');

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  win.loadFile('index.html');
};

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

預加載

const { contextBridge } = require('electron');
const { shell } = require('electron');

contextBridge.exposeInMainWorld('bridge', {
  electron: () => process.versions.electron,
  buttonClick: (link) => shell.openPath(link)
});

渲染器

const information = document.getElementById('info');
information.innerText = `Electron (v${bridge.electron()})`;

const fileManagerBtn = document.getElementById('open-file-manager');

fileManagerBtn.addEventListener('click', (event) => {
  bridge.buttonClick('C:/Users')
});

應用程序啟動后單擊按鈕時出錯:

Uncaught Error: Cannot read properties of undefined (reading 'openPath')
    at HTMLButtonElement.<anonymous> (renderer.js:7:10)

我嘗試使用 ContextIsolation false 並且它在渲染器上幾乎沒有修改,所以我一定遺漏了一些東西。 請幫助我,我試圖尋找答案,但找不到。

當我重新閱讀 electron 文檔時,我終於明白了我的應用程序發生了什么。 似乎“shell”不能在“沙盒”腳本中使用,你猜怎么着,因為 electron v20.0.0 預加載腳本是一個沙盒腳本。

主進程可以加載 shell 條命令,因此使用 IPC 方法我能夠在不禁用 ContextIsolation 的情況下啟動文件資源管理器。

暫無
暫無

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

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