在Electron.js中进行确认

发布于 2025-02-08 19:52:34 字数 1044 浏览 4 评论 0 原文

我想制作一个消息框,其中包含“是”,并且在电子js应用程序中否定了按钮。我试图用对话框在电子中。但这没有用:

const electron = require('electron')
const { dialog } = electron
console.log(dialog) // undefined
const electron = require('electron')
const dialog = electron.remote.dialog
console.log(dialog) // Uncaught Error: Cannot read "dialog" of undefined (remote is undefined)

然后,我尝试使用对话框这是一个模块在NPM中。但这并没有做我想做的事情。当我单击确定或关闭窗口时,没有什么是或否按钮也返回了相同的响应:

const electron = require('electron')
const dialog = require('dialog')
dialog.info('Are you sure?', 'Confirmation', function(exitCode) {
        if (exitCode == 0) {
                // Should clicked OK (always response)
        }
        if (exitCode == 1) {
                // Should closed window (but never works)
        }
})

我做错了什么?

I want to make a message box which contains yes and no buttons in a electron.js app. I tried to do it with dialog inside the electron. But it didn't work:

const electron = require('electron')
const { dialog } = electron
console.log(dialog) // undefined
const electron = require('electron')
const dialog = electron.remote.dialog
console.log(dialog) // Uncaught Error: Cannot read "dialog" of undefined (remote is undefined)

Then, I tried to do it with dialog which is a module in npm. But it didn't do the thing that I want to do. There wasn't any yes or no buttons also it returned the same responses when I clicked OK or I closed window:

const electron = require('electron')
const dialog = require('dialog')
dialog.info('Are you sure?', 'Confirmation', function(exitCode) {
        if (exitCode == 0) {
                // Should clicked OK (always response)
        }
        if (exitCode == 1) {
                // Should closed window (but never works)
        }
})

What did I do wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流殇 2025-02-15 19:52:34

您将要使用
Electron's
方法。



我已经将对话框的创建和管理放在 main.js 文件中。如果您想将其转移到它的
自己的文件,这不是问题。您需要做的就是 get()如果您需要对话框
框成为主窗口的孩子。

main.js (主过程),

// Import required Electron modules
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronDialog = require('electron').dialog;
const electronIpcMain = require('electron').ipcMain;

// Import required Node modules
const nodePath = require('path');

// Prevent garbage collection
let window;

function createWindow() {
    const window = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    window.loadFile('index.html')
        .then(() => { window.show(); });

    return window;
}

electronApp.on('ready', () => {
    window = createWindow();
});

electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// ---

electronIpcMain.on('openDialog', () => {
    electronDialog.showMessageBox(window, {
        'type': 'question',
        'title': 'Confirmation',
        'message': "Are you sure?",
        'buttons': [
            'Yes',
            'No'
        ]
    })
        // Dialog returns a promise so let's handle it correctly
        .then((result) => {
            // Bail if the user pressed "No" or escaped (ESC) from the dialog box
            if (result.response !== 0) { return; }

            // Testing.
            if (result.response === 0) {
                console.log('The "Yes" button was pressed (main process)');
            }

            // Reply to the render process
            window.webContents.send('dialogResponse', result.response);
        })
})

以进行过程之间的正确通信,我们必须
使用 Inter-Process Communication

PRELOAD.JS (主要进程)

// Import the necessary Electron modules
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;

// Exposed protected methods in the render process
contextBridge.exposeInMainWorld(
    // Allowed 'ipcRenderer' methods
    'ipcRenderer', {
        // From render to main
        openDialog: () => {
            ipcRenderer.send('openDialog');
        },
        // From main to render
        dialogResponse: (response) => {
            ipcRenderer.on('dialogResponse', response);
        }
    }
);

最后,您的 index.html 文件将侦听按钮单击。单击后,将消息发送到主过程以打开

对话框。

一旦从对话框中收到有效的响应,就会将响应发送回渲染过程进行处理。

ps:渲染
方法 /a>
可以使用而不是
/a>方法。
但是,如果是这样,您需要在渲染过程中处理“否”或逃生(ESC)响应。


index.html (渲染过程)

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Electron Test</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
    </head>

    <body>
        <input type="button" id="openDialog" value="Show Dialog">

        <hr>

        <div id="response"></div>
    </body>

    <script>
        // Open dialog (in main process) when "Show Dialog" button is clicked
        document.getElementById('openDialog').addEventListener('click', () => {
            window.ipcRenderer.openDialog('openDialog');
        })

        // Response from main process
        window.ipcRenderer.dialogResponse((event, response) => {
            if (response === 0) {
                // Perform your render action here
                document.getElementById('response').innerText = 'The "Yes" button was clicked';
            }
        });
    </script>
</html>

在对话框中使用超过2个按钮,在创建对话框中,您可能需要指定
取消,并在操作任何操作之前检查所有有效的返回值。

You will want to use
Electron's dialog.showMessageBox();
method.

The dialog.showMessageBoxSync();
method would block your main process until a response is received, so you won't want to use that unless intended.


I have placed the creation and management of your dialog box in the main.js file. If you want to move this into its
own file, that's not a problem. All you would need to do is get() the (main) window instance if you want your dialog
box to be a child of the main window.

main.js (main process)

// Import required Electron modules
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronDialog = require('electron').dialog;
const electronIpcMain = require('electron').ipcMain;

// Import required Node modules
const nodePath = require('path');

// Prevent garbage collection
let window;

function createWindow() {
    const window = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    window.loadFile('index.html')
        .then(() => { window.show(); });

    return window;
}

electronApp.on('ready', () => {
    window = createWindow();
});

electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// ---

electronIpcMain.on('openDialog', () => {
    electronDialog.showMessageBox(window, {
        'type': 'question',
        'title': 'Confirmation',
        'message': "Are you sure?",
        'buttons': [
            'Yes',
            'No'
        ]
    })
        // Dialog returns a promise so let's handle it correctly
        .then((result) => {
            // Bail if the user pressed "No" or escaped (ESC) from the dialog box
            if (result.response !== 0) { return; }

            // Testing.
            if (result.response === 0) {
                console.log('The "Yes" button was pressed (main process)');
            }

            // Reply to the render process
            window.webContents.send('dialogResponse', result.response);
        })
})

For proper communication between processes, we must
use Inter-Process Communication.

preload.js (main process)

// Import the necessary Electron modules
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;

// Exposed protected methods in the render process
contextBridge.exposeInMainWorld(
    // Allowed 'ipcRenderer' methods
    'ipcRenderer', {
        // From render to main
        openDialog: () => {
            ipcRenderer.send('openDialog');
        },
        // From main to render
        dialogResponse: (response) => {
            ipcRenderer.on('dialogResponse', response);
        }
    }
);

Finally, your index.html file will listen for a button click. Once clicked, send a message to the main process to open
the
dialog box.

Once a valid response is received from the dialog box, the response is sent back to the render process for processing.

PS: The render
method ipcRenderer.invoke()
could be used instead of
the ipcRenderer.send() method.
But if it was, you would need to handle the "No" or escape (ESC) response in the render process.

index.html (render process)

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Electron Test</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
    </head>

    <body>
        <input type="button" id="openDialog" value="Show Dialog">

        <hr>

        <div id="response"></div>
    </body>

    <script>
        // Open dialog (in main process) when "Show Dialog" button is clicked
        document.getElementById('openDialog').addEventListener('click', () => {
            window.ipcRenderer.openDialog('openDialog');
        })

        // Response from main process
        window.ipcRenderer.dialogResponse((event, response) => {
            if (response === 0) {
                // Perform your render action here
                document.getElementById('response').innerText = 'The "Yes" button was clicked';
            }
        });
    </script>
</html>

To use more than 2 buttons in your dialog box(es), in the creation of your dialog box you may want to designate
a cancelId and check for all valid return values before actioning anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文