Wednesday, February 7, 2024

[SOLVED] electron - Having trouble with showOpenDialog

Issue

Developing an electron app right now. I need the feature to upload files locally, I was experimenting with showOpenDialog(). Clicking on the button to upload, opens the file chooser as intended, but an error shows up in the terminal:

[4801:0205/172224.193666:ERROR:browser_main_loop.cc(276)] GLib-GObject: invalid cast from 'GtkFileChooserNative' to 'GtkWidget'

Choosing a file throws another error:

[4801:0205/172226.571068:ERROR:browser_main_loop.cc(276)] GLib-GObject: ../glib/gobject/gsignal.c:2777: instance '0x12b000ac7bf0' has no handler with id '3139'

Here's the code in my main.js:

ipcMain.handle('gallery-add-files', (e) => {
    var files = dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
        properties:[
            'openFile',
            'multiSelections'
        ]
    }, function(files){
        console.log(files)
    });
})

I'm using arch and I think that's relevant because previously there were a couple more errors showing with this one but installing 'xdg-desktop-portal' and 'xdg-desktop-portal-gtk' solved them.

Solution

I solved the issue, no errors in the terminal and working as intended, by switching showOpenDialog() to showOpenDialogSync().

It was a desperate attempt but it worked and I think is because showOpenDialog() returns at least two variables (canceled and filePaths) while I was trying to attribute it to a single variable.

I realized it after reading the answer to the post, that also works, which is why I marked it as the solution. Even though it still throws those errors in the terminal.


Solution

ipcMain.handle('gallery-add-files', async (e) => {
    try {
        const { canceled, filePaths } = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
            properties: ['openFile', 'multiSelections']
        });
        if (!canceled) {
            console.log(filePaths);
            // Process the selected files
        }
    } catch (error) {
        console.error('Failed to open dialog:', error);
    }
});


Answered By - Juan Manuel Garcia Montealegre
Answer Checked By - Katrina (WPSolving Volunteer)