Electron: Cannot access dialog before initialization

一曲冷凌霜 提交于 2021-02-05 11:05:10

问题


I have a renderer file that has the sole purpose of opening a dialog box to select files from. I have tried rewriting this so many times, and each time I get a different error. What am I doing wrong?

Exact code:

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

Related HTML:

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

Error Code

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

Using Electron: "7.1.7"


回答1:


Since Electron 6.0.0, the functions dialog.showMessageBox(), dialog.showOpenDialog() and dialog.showSaveDialog() return Promises and no longer take callback functions.

There are synchronous counterparts dialog.showMessageBoxSync(), dialog.showOpenDialogSync() and dialog.showSaveDialogSync().

Check out the following code examples showing the asynchronous and the synchronous way of displaying an open dialog:

Asynchronous: 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)
})

Synchronous: 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)
}

Both versions can optionally take a BrowserWindow as the first element. If one is provided, the dialog is shown as a modal window.

Check the Electron dialog documentation for detailed usage information.



来源:https://stackoverflow.com/questions/59698444/electron-cannot-access-dialog-before-initialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!