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

问题描述

我正在尝试使用预加载脚本解决.但是,我无法运行预加载脚本.一个最小的复制情况:

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"
  }
}

main.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>

无论我为 webSecurity nodeIntegration contextIsolation 使用什么设置,似乎我的 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',

但这可以像宣传的那样工作:

But this works as advertised:

      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不运行我的预加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 04:41