首页 > 解决方案 > 电子回调只能调用一次

问题描述

我有一个简单的电子应用程序,它包含一个提示输入用户名和密码的网络应用程序。

问题:

1) 当用户输入错误的凭据并且 authWindow 再次出现。使用正确的凭据不会发生第二次登录。

2) 当用户两次输入错误的凭据时,authWindow 不再出现。

任何帮助表示赞赏。

这是我的代码:

const { app, BrowserWindow, ipcMain } = require('electron');

app.on("login", (event, webContents, request, authInfo, callback) => {
  event.preventDefault();

  createAuthWindow().then(credentials => {
    callback(credentials.username, credentials.password);
  });
});

function createAuthWindow() {
  authWindow = new BrowserWindow({
    show: false,
    width: 400, 
    height: 200, 
    webPreferences: {
      nodeIntegration: true
    },
    title: "Authentication",
  });

  authWindow.on('ready-to-show', function (){
    authWindow.show();
  });

  authWindow.loadFile('password-form.html');

  return new Promise((resolve, reject) => {
    ipcMain.once('password-form-submission', (event, username, password) => {
      authWindow.close();
      const credentials = {
        username,
        password
      };
      resolve(credentials);
    });
  });
}

function createChatWindow() {
    chatWindow = new BrowserWindow({
        show: false,
        width: 1000, 
        height: 800, 
        webPreferences: {
            devTools: true
        },
        icon: __dirname + '/build/icon.png',
        title: "Messenger",
    });

    chatWindow.once('ready-to-show', function (){
      chatWindow.show();
    });

    chatWindow.loadURL('https://example.com');
    chatWindow.webContents.openDevTools();
}

app.on('ready', createChatWindow);

标签: electron

解决方案


更新:在 Electron 8 中,此问题似乎已解决,因此您无需执行下述解决方法。

我也遇到过这个问题,这就是我最终要做的......

我不得不使用这个 Electron ClientRequestapi 才能重试更多次。

您的“登录”事件处理程序将如下所示

const { app, BrowserWindow, ipcMain, net } = require('electron');

app.on("login", (event, webContents, request, authInfo, callback) => {
  event.preventDefault();

  let username = "";
  let password = "";

  const req = net.request({
    method: request.method,
    url: request.url
  });

  req.on("response", response => {
    console.log(response);
    if (response.statusCode > 400) {
      console.error("something went wrong");
      callback("", "");
    } else {
      console.log("we are good, request was successful"); // the request was authenticated correctly
      callback(username, password);
    }
    response.on("error", err => {
      console.error("something went wrong, response error", err);
      callback("", "");
    });
  });

  req.on("login", (loginAuthInfo, loginCallback) => {
    this.createAuthPrompt().then(credentials => {
      username = credentials.username;
      password = credentials.password;
      loginCallback(username, password);
    });
  });

  req.end();
});

推荐阅读