electron直接使用prompt的时候,会出现如下报错:
Google之后发现electron废弃了对prompt的支持,这时候我的第一想法是引入一个第三方库支持,在网上找到了GitHub - p-sam/electron-prompt: Electron helper to prompt for a string value:
接下来进行引入,需要用到electron的进程间通信,因为我的js是分开加载的,在不同的js中,而库的引入需要在electron初始化的时候进行:
preload.js:
const {contextBridge, ipcRenderer} = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
getPlatform: async () => await ipcRenderer.invoke('platform:get'),
openPrompt: async (options) => await ipcRenderer.invoke('prompt-for-book-name', options)
});
main.js:
const {app, BrowserWindow, ipcMain} = require('electron');
const {join} = require('path');
const electronPrompt = require('electron-prompt');
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
autoHideMenuBar: true,
icon: 'icon.png',
webPreferences: {
preload: join(__dirname, "preload.js"),
sandbox: false,
contextIsolation: true, // 启用上下文隔离
enableRemoteModule: false, // 因为你正在使用 contextBridge,所以这应该设置为 false
nodeIntegration: false, // 推荐禁用 nodeIntegration
webSecurity: false,
cache: false
}
});
win.loadFile('index.html');
};
app.whenReady().then(() => {
ipcMain.handle("platform:get", () => {
return process.platform;
});
ipcMain.handle('prompt-for-book-name', async (event, options) => {
return electronPrompt(options);
});
createWindow();
});
然后在需要使用prompt框的文件中这样使用:
function renameBook(id) {
window.electronAPI.openPrompt({
title: 'Rename Book',
label: 'Enter new book name:',
type: 'input'
})
.then((newBookName) => {
if (!newBookName) {
alert('Book name cannot be empty!');
return;
}
fetch(`http://localhost:8080/book/edit/${userInfo.id}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({bookname: newBookName})
})
.then(response => response.json())
.then(data => {
if (data.code === 0) {
alert('Book renamed successfully!');
fetchBooks(1); // Refresh the book list
} else {
alert('Error renaming book: ' + data.message);
}
})
.catch(error => {
alert('Network or server error: ' + error);
});
})
.catch(console.error);
}
参考资料:
GitHub - p-sam/electron-prompt: Electron helper to prompt for a string value
进程间通信 | Electron (electronjs.org)
参与讨论
(Participate in the discussion)
参与讨论