没有运行我的预加载脚本

没有运行我的预加载脚本

本文介绍了为什么 Electron 没有运行我的预加载脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 预加载脚本 来解决 CORS 标头问题 在 Electron 4.2.3 中.但是,我无法运行预加载脚本.最小复制案例:

I'm trying to use a preload script to work around a CORS header issue in Electron 4.2.3. However, I can't get the preload script to run. A minimal reproduction case:

package.json

{
  "name": "your-app",
  "version": "0.1.0",
  "main": "main.js",
  "dependencies": {
    "electron": "^4.2.3"
  }
}

ma​​in.js

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

app.on('ready', function() {
  const win = new BrowserWindow({
    webPreferences: {
      preload: `file://${__dirname}/preload.js`,
    }
  })
  win.webContents.openDevTools()
  win.loadFile('index.html')
})

preload.js

window.preloadWasRun = 'preload was run'

index.html

<body>
  <script>
    document.write(window.preloadWasRun || 'preload was not run')
  </script>
</body>

无论我对 webSecuritynodeIntegrationcontextIsolation 使用什么设置,似乎我的 preload 脚本只是被忽略了.即使我在脚本中出现语法错误,它也不会在任何地方显示任何错误.

No matter what settings I use for webSecurity, nodeIntegration and contextIsolation, it seems that my preload script is just getting ignored. Even if I make a syntax error in the script, it doesn't show any errors anywhere.

推荐答案

原来它必须是绝对路径名,而不是绝对 URL.这些都不起作用:

Turns out it has to be an absolute path name, not an absolute URL. None of these work:

      preload: `file://${__dirname}/preload.js`,
      preload: './preload.js',
      preload: 'preload.js',

但这就像宣传的那样:

      preload: `${__dirname}/preload.js`,

由于它似乎是文件系统路径而不是 URL,因此使用 path.join 来代替具有奇怪路径分隔符的平台可能是明智的:

Since it seems to be a filesystem path rather than a URL, it might also be wise to use path.join instead, to account for platforms with weird path separators:

      preload: path.join(__dirname, 'preload.js'),

这篇关于为什么 Electron 没有运行我的预加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 21:40