Amir Shabani
Amir Shabani

Reputation: 4197

Uncaught ReferenceError: dialog is not defined

I'm trying to create a button in that opens a dialog to open a file. (and in this example, simply print its name)

This is the button in my index.html:

 <div class="alse-element">
     <input id="select-song" type="button" value="select song" onclick="select_song()"/>
 </div>

From dialog | Electron, it is said to import dialog in a renderer file like this:

const { dialog } = require('electron').remote
console.log(dialog)

So this is my renderer.js:

const { dialog } = require('electron').remote

function select_song() {
    dialog.showOpenDialog(
        {properties: ['openFile']}, 
        filename => {
            console.log(filename)
        }
    )
}

However, when I press the button, this message is printed in the console:

Uncaught ReferenceError: dialog is not defined
    at select_song (renderer.js:4)
    at HTMLInputElement.onclick (index.html:14)

I tried Philip's answer:

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

But it didn't work (same error)


I tried Edgar Martinez's answer:

var remote = require('remote');
var dialog = remote.require('dialog');

But I get this error (and if use const instead of var, I get the same error as above):

Uncaught TypeError: Cannot read property 'showOpenDialog' of undefined
    at select_song (renderer.js:5)
    at HTMLInputElement.onclick (index.html:14)

I tried D.Richard's answer:

const remote = require('electron').remote 
const dialog = remote.dialog;

But it didn't work either (same error)


How can I fix this?

Upvotes: 0

Views: 7030

Answers (1)

Amir Shabani
Amir Shabani

Reputation: 4197

The problem was that I didn't notice the require is not defined at the top of console.

enter image description here

After searching for it, I found Sathiraumesh's answer, and after adding webPreferences: {nodeIntegration: true} to the main.js file:

main_window = new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    webPreferences: {
        nodeIntegration: true
    }
})

The same code, suggested in Electron documenation, works:

const {dialog} = require('electron').remote

function select_song() {
    dialog.showOpenDialog(
        {properties: ['openFile']}, 
        filename => {
            console.log(filename)
        }
    )
}

enter image description here

Upvotes: 1

Related Questions