Matthew Mulhall
Matthew Mulhall

Reputation: 63

Electron: Cannot access dialog before initialization

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"

Upvotes: 4

Views: 3156

Answers (1)

snwflk
snwflk

Reputation: 3527

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.

Upvotes: 1

Related Questions