首页 > 解决方案 > 从 Angular 组件访问 Electron API

问题描述

我正在寻找通过电子加载本地保存的视频文件并在我的角度组件中播放它。为此,我公开了 loadLocalFile 函数,以避免将 nodeIntegration 设置为 true。我仍然收到此安全警告:

此渲染器进程没有设置内容安全策略或启用了“unsafe-eval”的策略。这会使该应用程序的用户面临不必要的安全风险。

我使用 Angular 时没有 renderer.js 文件。我打算如何在我的 Angular 中访问我的电子 API?

我的 Preload.js 包含以下内容,我想从我的 Angular 组件中调用它们:

contextBridge.exposeInMainWorld("electronAPI", {
  loadLocalFile: (event, filePath) => {
    if (filePath === undefined) {
      console.log("No file selected");
      return;
    }

    dialog.showOpenDialog((filePath) => {
      // fileNames is an array that contains all the selected
      if (filePath === undefined) {
        console.log("No file selected");
        return;
      }

      fs.readFile(filePath, "utf-8", (err, data) => {
        if (err) {
          alert("An error ocurred reading the file :" + err.message);
          return;
        }

        // Change how to handle the file content
        console.log("The file content is : " + data);
      });
    });
  },
});

我的 app.module.ts 包含以下内容:

export interface IElectronAPI {
  loadLocalFile: (event: Event | null, path: string) => Promise<void>;
}

declare global {
  interface Window {
    electronAPI: IElectronAPI;
  }
}

在我的 Angular 组件中,我通过以下方式访问 Api:

window.electronAPI.loadLocalFile(null, "/path/to/my/video");

您打算如何从 Angular 组件实现电子 API 访问?一项服务可能会运作良好,但我找不到或想出一个不会因删除某些导入而被破坏的工作示例

标签: javascriptnode.jsangularelectron

解决方案


你可以使用 ngx-electron。这有助于您更轻松地从渲染器进程调用 Electron API。您可以轻松地在 Angular 项目中使用。但我不确定它是否有助于读取视频文件。


推荐阅读