首页 > 解决方案 > 电子.getWebContents().on('login',..) 只调用一次

问题描述

我正在尝试在 webview 元素上使用代理,但是当我在设置代理后尝试更改代理时,它不会调用“登录”并第一次使用为代理提供的相同凭据。

代码:

newWebView.getWebContents().on('login', (event, request, authInfo, callback) => {
    event.preventDefault();

    if (authInfo.isProxy) {
        console.log("Proxy set")
        callback(username, password)
    }
});

但是代码只被调用一次。

我什至正在初始化一个新的 webview 元素并设置新的“登录”事件,但它仍然没有被解雇。

我的想法是,因为 ip 具有相同的端口和 ip,它将保持默认凭据,但我需要更改 webview 中代理的身份验证凭据。

这将如何完成?

标签: node.jswebviewproxyelectron

解决方案


当想要进行基本身份验证时,login将发出应用程序的事件。webContents

  const { app } = require('electron')
  app.on("login", (event, webContents, request, authInfo, cb) =>
    tryProxyLogin(webContents, event, request, authInfo, cb)
  );

   /**
   *
   * @param {Electron.webContents} webContents
   * @param {Electron.Event} event
   * @param {Electron.Request} request
   * @param {Electron.AuthInfo} authInfo
   * @param {(username:string,password:string)=>void} cb
   */
  const tryProxyLogin = (webContents, event, request, authInfo, cb) => {
    try {
      const contentId = webContents.id;

      const { username, password } = {
        username: XXXXX,
        password: XXXXX
      };

      if (authInfo.isProxy && username && password) {

        //temp solution about this issue
        //https://github.com/electron/electron/issues/16010

        if (!authInfo.realm) {
          setTimeout(() => {
            webContents.reload();
          }, 500);
          return;
        }

        const { country, sessionId } = {
            country: 'XXXXX',
            sessionID: 'xxxxxxx-xxxxxxx'
        };

        if (country && sessionId) {
          event.preventDefault();
          console.debug(
            "proxy ready to login",
            `customer-${username}-cc-${country}-sessid-${sessionId}`
          );

          cb(
            `customer-${username}-cc-${country}-sessid-${sessionId}-${Date.now()}`,
            password
          );
        }
      }
    } catch (error) {
      console.error(error);
    }
  };

这是基于 Electron v4.2.0


推荐阅读