简体   繁体   English

Electron - 防止 window 关闭但允许重定向

[英]Electron - prevent window close but allow redirects

I have a simple Electron app.我有一个简单的 Electron 应用程序。 The main process would open up a browser window (I call it mainWindow ) and I would like to prevent users from closing it (for kiosk purposes; FYI, I already have kiosk: true . I'm just trying to add another layer of protection).主要过程将打开一个浏览器 window (我称之为mainWindow ),我想阻止用户关闭它(用于信息亭目的;仅供参考,我已经有kiosk: true 。我只是想添加另一层保护)。

I have set up a beforeunload event listener in my renderer process like shown below:我在渲染器进程中设置了一个beforeunload事件侦听器,如下所示:

window.onbeforeunload = (e) => {
   console.log('I do not want to be closed')
   e.returnValue = false 
}

This works well.这很好用。 It prevents closing of the window in every way (at least in macOS) and I could quit the process with mainWindow.destroy() in the main process.它可以防止 window 以各种方式关闭(至少在 macOS 中),我可以在主进程中使用mainWindow.destroy()退出该进程。 However, by doing this, I am not able to redirect my window to any other HTML files, no matter with location.href or mainWindow.loadFile() because it would fire the beforeunload event and prevent it from redirecting.但是,通过这样做,我无法将我的 window 重定向到任何其他 HTML 文件,无论location.hrefmainWindow.loadFile()因为它会触发beforeunload事件并阻止它重定向。

One solution I could think of is to use a fullscreen iframe in mainWindow and do the redirections there, but the communication between sandboxed iframe and the window that uses ipcRenderer would be too complex.我能想到的一种解决方案是在mainWindow中使用全屏iframe并在那里进行重定向,但是沙盒iframe和使用ipcRenderer的 window 之间的通信太复杂了。

Apart from that, is there a work around to distinguish whether a beforeunload event was fired for it being closed or just being redirected?除此之外,是否有解决方法来区分beforeunload事件是因为它被关闭还是被重定向而被触发?

Instead of using the DOM onbeforeunload handler, you could listen for the BrowserWindow 's very own close event in the Main Process, which is emitted before onbeforeunload but only when the window is actually going to close.除了使用 DOM onbeforeunload处理程序,您还可以在主进程中侦听BrowserWindow自己的close事件,该事件在onbeforeunload之前发出,但仅在 window 实际要关闭时发出。

As per the documentation , you would have to call e.preventDefault () to prevent closing, but you wouldn't have to worry about page redirects.根据文档,您必须调用e.preventDefault ()来防止关闭,但您不必担心页面重定向。

const { BrowserWindow } = require ("electron");

let window;
// However you're initialising your BrowserWindow...

window.on ("close", event => {
    event.preventDefault ();
});

The documentation for #destroy () states that it will not emit the "close" event, thus everything should work as before, except you're listening for the event on the Main Process and gain window reloading. #destroy ()的文档声明它不会发出"close"事件,因此一切都应该像以前一样工作,除非您正在主进程上监听事件并获得 window 重新加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM