【问题标题】:jquery and fs dont work together in angular electron app (using ngx-electron)jquery 和 fs 在角度电子应用程序中不能一起工作(使用 ngx-electron)
【发布时间】:2021-09-29 04:02:12
【问题描述】:

所以我有一个 Angular 应用程序,其中有 jquery 库,在组件中,我有

included declare var $;
ngOnInit(){$(document).ready{....}}

我已经安装了 ngx-electron 来导入 fs 库。

import {ElectronService} from 'ngx-electron'
constructor(private _electronService: ElectronService) { 
    this.fs = this._electronService.remote.require('fs');
}

现在要让 ngx-electron 工作,我必须在 main.js 文件中设置以下内容:

webPreferences: { 
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: false
    }

但是,当我这样做时,jquery 会停止在浏览器上加载(未定义 jquery)。如果没有这些 web 首选项,jquery 可以正常工作,但是 this._electronService.remote 返回 null。如何让 Jquery 和 fs (ngx-electron) 同时工作?

【问题讨论】:

    标签: javascript node.js angular electron


    【解决方案1】:

    好的,过去 24 小时我深入兔子洞,对角度和电子如何协同工作以及电子渲染器如何工作有了更好的了解。

    问题的解决方案是使用 preload.js,如下所示:

    https://github.com/electron/electron/issues/9920#issuecomment-575839738

    所以一个小补充——为了让它在组件内部而不是从 index.html 中使用 angular,我们可以跳过 index.html 中上面注释中的行。而是将其放入您的组件中。此外,您需要使用 const win = (window) 将全局窗口对象提取到您的组件中

    main.js preload.js

    Use the link above for both main.js and preload.js
    

    组件.ts

    const win = (<any>window)
    
    ngOnInit(){
    win.api.receive("fromMain", (data) => {
            console.log(`Received ${data} from main process`);
        });
    win.api.send("toMain", "some data");
    

    此解决方案从安全角度和渲染角度都有效。我不需要改变我的角度应用程序让 jquery 与电子一起工作。此外,对 fs 对象的任何访问都可以从 main.js 文件完成,结果可以通过 api 返回到 Angular 应用程序,而不是通过设置 nodeIntegration 直接尝试从 Angular 应用程序访问文件系统(fs) : true, contextIntegration:false 等在 web 首选项中。 因此,总而言之,ngx-electron 并不理想,因为它依赖于将 nodeIntegration 设置为 true。

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 2019-02-20
      • 2019-01-21
      • 2018-01-17
      • 2019-04-06
      • 2020-10-08
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多