我是第一次与Electron JS合作,与Reaction JS一起工作.

我试图在窗口打开/关闭时发出HTTP请求,但不知道如何进行.从基本的控制台日志(log)中,我发现当我从浏览器关闭应用程序时,以下两个函数会被触发.在应用程序关闭之前,我正在try 发出一个更新用户登录状态的HTTP请求.

const logout = async (_data) => {
return await axios.PUT('URL_HERE', _data)
}
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {

    logout(someData)
    app.quit()
  }
})
 mainWindow.on('closed', function() {
    logout(someData)

    mainWindow = null
  })

我的index.js(没有index.html文件)文件如下所示:

import React from 'react'
import { render } from 'react-dom'
import App  from "./components/App"

let root = document.createElement('div')

root.id = 'root'
document.body.appendChild(root)

render(<App />, document.getElementById('root'))

我该怎么做呢?任何帮助都是我们非常感激的.

推荐答案

要在Electron中打开或关闭窗口时发出HTTP请求,可以使用ipcRenderer.send()方法.此方法允许您从呈现器进程向主进程发送消息.

要使用ipcRenderer.send(),您首先需要创建一个IPC通道.这可以通过调用ipcRenderer.createChannel()方法来完成.此方法的第一个参数是通道的名称.

一旦创建了IPC通道,就可以通过调用ipcRenderer.send()方法向主进程发送消息.此方法的第一个参数是通道的名称,第二个参数是消息.

主进程将接收该消息,然后可以采取它需要的任何操作.在您的例子中,您可以使用该消息发出更新用户登录状态的HTTP请求.

下面是一个在窗口打开或关闭时如何使用ipcRenderer.send()发出HTTP请求的示例:

// Create an IPC channel
const channel = ipcRenderer.createChannel('my-channel');
​
// Send a message to the main process when the window is opened
ipcRenderer.on('window-open', () => {
  channel.send('open');
});
​
// Send a message to the main process when the window is closed
ipcRenderer.on('window-close', () => {
  channel.send('close');
});
​
// In the main process, listen for messages from the renderer process
ipcMain.on('my-channel', (event, message) => {
  // Make an HTTP request to update the user's login status
  fetch('https://example.com/api/update-login-status', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      username: 'user@example.com',
      loggedIn: true,
    }),
  });
});

我希望这能帮到你!

Javascript相关问答推荐

JavaScript .Click()函数不起作用

仅圆角的甜甜圈图表

有条件的悲剧

通过嵌套模型对象进行Mongoose搜索

我不知道为什么setwritten包装promise 不能像我预期的那样工作

我可以从React中的出口从主布局调用一个处理程序函数吗?

自定义高图中的x轴标签序列

如何从html元素创建树 struct ?

如何从Intl.DateTimeFormat中仅获取时区名称?

如何控制Reaction路由加载器中的错误状态?

同一类的所有div';S的模式窗口

我想将Sitecore搜索面过滤器从多个转换为单个

为什么云存储中的文件不能公开使用?

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

如何根据查询结果重新排列日期

如何修复错误&语法错误:不能在纯react 项目中JEST引发的模块&之外使用导入语句?

P5JS-绘制不重叠的圆

如何在独立的Angular 应用程序中添加Lucide-Angel?

AG-GRIDreact 显示布尔值而不是复选框

如何将字符串拆分成单词并跟踪每个单词的索引(在原始字符串中)?