docs: add IPC doc (#32059)

* docs: add IPC doc

* fix: use "string" primitive

* use 'string' ipcrenderer

* use "number" primitive

* Update docs/tutorial/ipc.md

Co-authored-by: Jeremy Rose <nornagon@nornagon.net>

* Update docs/tutorial/ipc.md

Co-authored-by: Jeremy Rose <nornagon@nornagon.net>

* add code sample

Co-authored-by: Jeremy Rose <nornagon@nornagon.net>
This commit is contained in:
Erick Zhao 2022-02-09 08:00:05 -08:00 committed by GitHub
parent 254dbd7400
commit e9a43be9be
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 798 additions and 184 deletions

View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Dialog</title>
</head>
<body>
<button type="button" id="btn">Open a File</button>
File path: <strong id="filePath"></strong>
<script src='./renderer.js'></script>
</body>
</html>

View file

@ -0,0 +1,32 @@
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
async function handleFileOpen() {
const { canceled, filePaths } = await dialog.showOpenDialog()
if (canceled) {
return
} else {
return filePaths[0]
}
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.handle('dialog:openFile', handleFileOpen)
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})

View file

@ -0,0 +1,5 @@
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI',{
openFile: () => ipcRenderer.invoke('dialog:openFile')
})

View file

@ -0,0 +1,7 @@
const btn = document.getElementById('btn')
const filePathElement = document.getElementById('filePath')
btn.addEventListener('click', async () => {
const filePath = await window.electronAPI.openFile()
filePathElement.innerText = filePath
})