【问题标题】:Accessing Electron API from Angular Component从 Angular 组件访问 Electron API
【发布时间】:2021-12-25 13:04:28
【问题描述】:

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

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

我没有 renderer.js 文件,因为我使用的是 Angular。我应该如何在 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 访问?一项服务可能会运行良好,但我找不到或想出一个没有因删除某些导入而破坏的工作示例

【问题讨论】:

    标签: javascript node.js angular electron


    【解决方案1】:

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

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 我已经看过 ngx-electron。不幸的是,它不适用于 Electron 15,因为它不导出 ngx-electron 所依赖的远程模块。
    • 这是我得到的错误:错误:node_modules/ngx-electron/lib/electron.service.d.ts:17:31 - 错误 TS2694:命名空间 'Electron.CrossProcessExports' 没有导出成员“远程”。 17 只读远程:Electron.Remote;
    • 您可以使用“@electron/remote”进行远程操作。然后像添加电子服务一样导入它。从'@electron/remote'远程导入*; @Injectable({ providedIn: 'root' }) 导出类 ElectronService { remote: typeof remote;获取 isElectron(): boolean { return !!(window && window.process && window.process.type); } constructor() { // 条件导入 if (this.isElectron) { this.remote = window.require('@electron/remote'); } }
    猜你喜欢
    • 2019-10-15
    • 2018-12-26
    • 1970-01-01
    • 2023-03-27
    • 2016-09-28
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多