【问题标题】:Electron: Cannot access dialog before initialization电子:初始化前无法访问对话框
【发布时间】:2020-01-12 07:02:33
【问题描述】:

我有一个渲染器文件,其唯一目的是打开一个对话框以从中选择文件。我已经尝试重写了很多次,每次都得到不同的错误。我做错了什么?

具体代码:

const { ipcRenderer, shell, remote } = require('electron')
const dialog = remote.dialog;

function openFileBrowser() {

    dialog.showOpenDialog(remote.getCurrentWindow(), {
        properties: ["openFile", "multiSelections"]
    }).then(result => {
        if (result.canceled === false) {
            console.log("Selected file paths:")
            console.log(result.filePaths)
        }
    }).catch(err => {
        console.log(err)
    })
}

相关 HTML:

        <div id="button-container">
            <nav>
                <ul class="buttons">
                    <li id="Open" onclick="openFileBrowser()">Proxies</li>
                </ul>
            </nav>
        </div>

错误代码

renderer.js:37 Uncaught ReferenceError: Cannot access 'dialog' before initialization
    at openFileBrowser (renderer.js:37)
    at HTMLLIElement.onclick (proxies.html:16)

使用电子: “7.1.7”

【问题讨论】:

  • edit 包含您遇到的确切错误以及重现该问题的完整但最小的 (!) 代码示例。另请说明您使用的 Electron 版本。
  • 我已经编辑了原始消息,对于不够清晰,我深表歉意。
  • 请添加一个完整的例子,即不仅仅是摘录。你的例子应该尽可能小,同时也暴露错误。通常,制作项目的副本并删除发生错误所不需要的所有内容是有意义的。那将是minimal reproducible example
  • @snwflk 做了一个新项目,试图重现这个问题,但我不能。这令人难以置信的沮丧。找到答案后,我会尝试发布。

标签: electron


【解决方案1】:

从 Electron 6.0.0 开始,dialog.showMessageBox()dialog.showOpenDialog()dialog.showSaveDialog() 函数返回 Promises,不再接受回调函数。

有同步对应dialog.showMessageBoxSync()dialog.showOpenDialogSync()dialog.showSaveDialogSync()

查看以下显示打开对话框的异步和同步方式的代码示例:

异步:dialog.showOpenDialog()

const remote = require("electron").remote
const dialog = remote.dialog

dialog.showOpenDialog(remote.getCurrentWindow(), {
    properties: ["openFile", "multiSelections"]
}).then(result => {
    if (result.canceled === false) {
        console.log("Selected file paths:")
        console.log(result.filePaths)
    }
}).catch(err => {
    console.log(err)
})

同步:dialog.showOpenDialogSync()

const remote = require("electron").remote
const dialog = remote.dialog

let result = dialog.showOpenDialogSync(remote.getCurrentWindow(), {
    properties: ["openFile", "multiSelections"]
})
if (typeof result === "object") {
    console.log("Selected file paths:")
    console.log(result)
}

两个版本都可以选择将 BrowserWindow 作为第一个元素。如果提供,则对话框显示为模式窗口。

查看Electron dialog documentation 了解详细使用信息。

【讨论】:

  • 感谢您的评论。这似乎无法解决问题。错误仍然存​​在:```未捕获的ReferenceError:在HTMLLIElement.onclick(proxies.html:16)的openFileBrowser(renderer.js:37)初始化之前无法访问'对话框'```这对我来说没有意义我加载和使用的每个其他模块都没有问题。我试图在启动时运行它并且它有效,它似乎与我从一个单独的 html 文件中调用它有关。这正常吗?
猜你喜欢
  • 2016-04-18
  • 2020-08-25
  • 2020-09-08
  • 2021-09-29
  • 2019-10-12
  • 2020-11-30
  • 2021-11-02
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多