alert(filePaths[0]);
}
</pre>
===ファイルを開く===
----
*コンテキストメニューからファイルを開くダイアログで選択したファイルを画面に表示
*main.js
<pre>
ipcMain.handle('open-context-menu', (ev, msg) => {
var win = BrowserWindow.getFocusedWindow();
let contextmenuTemplate = [
{
label: 'ファイルを開く', click() {
openFile(win);
}
}
];
const contextMenu = Menu.buildFromTemplate(contextmenuTemplate);
contextMenu.popup({window : win});
});
async function openFile(win) {
var result = await dialog.showOpenDialogSync(
win, {
properties: ['openFile'],
filters: [
{name:'text', extensions: ['txt'] },
{name:'all', extensions: ['*'] },
]
});
if (result.canceld) {
return;
}
var filePath = result[0];
var content = fs.readFileSync(filePath).toString();
win.webContents.send('open-file', content);
}
</pre>
*preload.js
<pre>
contextBridge.exposeInMainWorld(
"api",
{
openContextMenu: (type) => {
return ipcRenderer.invoke('open-context-menu', type);
},
on: (channel, callback) => {
ipcRenderer.on(channel, (event, argv)=>callback(event, argv))
}
}
);
</pre>
*index.html
<pre>
window.addEventListener('contextmenu', openContextMenu, false);
window.api.on('open-file', (event, content)=>{
document.getElementById('open_file').value = content;
});
</pre>