【问题标题】:alert(__dirname) not producing any output in an electron appalert(__dirname) 在电子应用程序中没有产生任何输出
【发布时间】:2020-09-14 19:35:15
【问题描述】:

运行以下电子应用程序时,我没有得到所需的输出,即包含 pwd 作为输出的警报框。但是, index.html 中的注释行似乎工作正常。 chromium 窗口的开发者控制台显示“未捕获的 ReferenceError: __dirname is not defined at HTMLButtonElement.”。此 sn-p 逐字逐句(注释行除外)摘自 Steve Kinney 2019 年版的《Electron in action》一书。

有什么建议吗?

package.json如下

{
  "name": "bookmarker",
  "version": "1.0.0",
  "description": "electron app",
  "main": "./app/main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Wasim Aftab",
  "license": "ISC",
  "dependencies": {
    "electron": "^9.0.0"
  }
}

main.js如下

const {app, BrowserWindow} = require('electron');
let mainWindow = null;
app.on ('ready', () => {
    console.log('Hello, from electron');
    mainWindow = new BrowserWindow();
    mainWindow.webContents.loadFile(__dirname + '/index.html');
});

index.html如下

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'unsafe-inline';
connect-src *">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Bookmarker</title>
</head>

<body>
    <h1>Hello from Electron</h1>
    <p>
        <button class="alert">Current Directory</button>
    </p>
</body>
<script>
    const button = document.querySelector('.alert');
    button.addEventListener('click', () => {
        alert(__dirname);
        // alert(window.location.pathname.replace(/[^\\\/]*$/, ''));
    });
</script>

</html>

【问题讨论】:

标签: javascript html electron


【解决方案1】:

__dirname是nodejs的概念,浏览器中不存在。

解决此问题的一种方法是将nodeIntegration 设置为true

mainWindow = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true
    }
});

另一种方法是使用预加载脚本(始终为预加载脚本启用 nodeIntegration):

mainWindow = new BrowserWindow({
    webPreferences: {
        preload: (__dirname + "/preload.js")
    }
});

然后在preload.js文件中:

window.__dirname = __dirname

【讨论】:

  • 感谢工作!我是这个领域的新手,我正在使用的书似乎有这种错误,你能给我推荐一本更好的书/资源来学习电子应用程序开发吗?
  • 我不是读书人,但official electron guide 看起来很有帮助。
  • @WasimAftab 如果您对答案感到满意,请点赞并接受。谢谢
【解决方案2】:

对于 electron v16.0.4,还需要添加 contextIsolation: false

$ npx electron --version
v16.0.4

    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      // enableRemoteModule: true,
    },
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多