Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by extension in Electron file dialog

How do I add a filter by extension in an Electron file dialog. For example:

function openDialogExample() {
    var remote = require('remote');
    var dialog = remote.require('dialog');

    return dialog.showOpenDialog(
      remote.getCurrentWindow(),
      {
          defaultPath: 'c:/',
          filters: [
              { name: 'All Files', extensions: ['*'] },
              { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
              { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }
            ],
          properties: ['openFile']
      }
    );
}

How do I implement it into my codebase?

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

document.getElementById('importWallet').onclick = () => {
    dialog.showOpenDialog((fileName) => {
        if(fileName !== undefined) {
            readWallet(fileName[0])
        }
    });
}

function readWallet(filePath) {
    fs.readFile(filePath, 'utf-8', (err, data) => {
        if(err) {
            alert('An error occured while importing your wallet', err)
            return
        }
    })
}
like image 746
methuselah Avatar asked Jan 25 '18 22:01

methuselah


2 Answers

step one: you must send a IPC from (main process) main.js to the (render Process) index.js. for more details read this, this and this.

step two: now you can processing openFile or openDirectory or ...

an example (of my code):

main.js: (with win.webContents.send(...); i send an ipc)

... after require some library in app.on("ready", () => {
   let appMenu = [
       {
            "label": "file",
            "submenu":
                [
                    {
                        "label": "open file",
                        "accelerator": "CmdOrCtrl+o",
                        click() {
                            showDialog("openFile");
                        },
                    }, // end ofshowSaveDialog "open file"
                    {
                        "label": "save file",
                        "accelerator": "CmdOrCtrl+s",
                        click() {
                            showDialog("saveFile");
                        },
                    }, // end of "save file"
                    {
                        "type": "separator"
                    },
                    {
                        "label": "open Directory",
                        "accelerator": "CmdOrCtrl+k+o",
                        click() {
                            showDialog("openDirectory");
                        },
                    }, // end ofshowSaveDialog "openDirectory"
                    {
                        "type": "separator"
                    },
                    {
                        "label": "exit app",
                        "accelerator": "CmdOrCtrl+X",
                        "role": "quit",
                    } // end of "exit"
                ], // end of "submenu file"
        }, // end of "file"
    ]
})
function showDialog(typeShowDialog) {
switch (typeShowDialog) {
    case "openFile":
    case "openDirectory":
        dialog.showOpenDialog(
            {
                "title": `${typeShowDialog}`,
                "properties": [`${typeShowDialog}`], // openDirectory, multiSelection, openFile
                "filters":
                    [
                        {
                            "name": "all",
                            "extensions": ["*"]
                        },
                        {
                            "name": "text file",
                            "extensions": ["txt", "text"]
                        },
                        {
                            "name": "html",
                            "extensions": ["htm", "html"]
                        },
                        {
                            "name": "style sheet",
                            "extensions": ["css"]
                        },
                        {
                            "name": "javascript",
                            "extensions": ["js"]
                        },
                        {
                            "name": "c++",
                            "extensions": ["cpp", "cc", "C", "cxx"],
                        },
                        {
                            "name": "json",
                            "extensions": ["json"]
                        },
                    ],
            }, // end of options: electron.OpenDialogOptions
            (filename) => {
                if (filename === undefined) {
                    return;
                }
                win.webContents.send(`${typeShowDialog}`, filename); // Sending Content to the Renderer Process this is a IPC
            }
        ); // end of "dialog.showOpenDialog"
        break;
    case "saveFile":
        dialog.showSaveDialog(
            {
                "title": `${typeShowDialog}`,
                "filters":
                    [
                        {
                            "name": "all",
                            "extensions": ["*"]
                        },
                        {
                            "name": "text file",
                            "extensions": ["txt", "text"]
                        },
                        {
                            "name": "html",
                            "extensions": ["htm", "html"]
                        },
                        {
                            "name": "style sheet",
                            "extensions": ["css"]
                        },
                        {
                            "name": "javascript",
                            "extensions": ["js"]
                        },
                        {
                            "name": "c++",
                            "extensions": ["cpp", "cc", "C", "cxx"],
                        },
                        {
                            "name": "json",
                            "extensions": ["json"]
                        },
                    ],
            }, // end of options: electron.SaveDialogOptions
            (filename) => {
                if (filename === undefined) {
                    return;
                }
                win.webContents.send(`${typeShowDialog}`, filename); // Sending Content to the Renderer Process this is a IPC
            }
        ); // end of "dialog.showSaveDialog"       
        break;
} // end of "switch"

} // end of "showDialog"

index.js: (with ipcRenderer.on(...); i receive ipc)

    ipcRenderer.on("openFile", (event, arg) => {
      // some sttements;
});

ipcRenderer.on("openDirectory", (event, arg) => {
     // some statements;
 });

ipcRenderer.on("saveFile", (event, arg) => {
    // some statements;
});

and this is a example about ipc

like image 109
Kasir Barati Avatar answered Nov 03 '22 21:11

Kasir Barati


You can add as many filters to your options object as you like. You just have to make sure you don't add them more than once - because there is no check on uniqueness.

index.html

<!DOCTYPE html>
<html>

<body>
    <button id="importWallet">Import wallet</button>
    <script src="./index.js"></script>
</body>

</html>

index.js

const app = require("electron").remote;
const fs = require("fs");
const dialog = app.dialog;

//customize this one as you like
const dialogOptions = {
  defaultPath: "c:/",
  filters: [
    { name: "All Files", extensions: ["*"] },
    { name: "Images", extensions: ["jpg", "png", "gif"] },
    { name: "Movies", extensions: ["mkv", "avi", "mp4"] }
  ],
  properties: ["openFile"]
};

document.getElementById("importWallet").onclick = () => {
  const unicornFilter = dialogOptions.filters.find(item => {
    if (item.name === "Unicorn") {
      return item;
    } else {
      return undefined;
    }
  });

  if (!unicornFilter) {
    const myUnicornFilter = {
      name: "Unicorn",
      extensions: ["unicorn", "horse"]
    };
    dialogOptions.filters.push(myUnicornFilter);
  }

  dialog.showOpenDialog(dialogOptions, fileName => {
    if (fileName !== undefined) {
      console.log(fileName);
      readWallet(fileName[0]);
    }
  });
};

function readWallet(filePath) {
  fs.readFile(filePath, "utf-8", (err, data) => {
    if (err) {
      alert("An error occured while importing your wallet", err);
      return;
    }
  });
}
like image 3
Rhayene Avatar answered Nov 03 '22 21:11

Rhayene