Передача входной переменной между 2 HTML файлами с использованием Electron с системой входа - PullRequest
0 голосов
/ 29 февраля 2020

В настоящее время я создаю приложение, использующее Electron, которое позволит пользователям общаться друг с другом через socket.io. Я сделал экран входа в систему, на котором пользователи вводят свою электронную почту и пароль, которые они зарегистрировали, чтобы получить доступ к главному меню. В этом случае я использовал фиктивную учетную запись для тестирования.

Вот код для login.html вместе с файлом login_scripts.js:

login.html:

<html>
  <!--Required JQuery script-->
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>

  <head>
    <!--Required meta tags-->
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' 'unsafe-eval';" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--Required CSS-->
    <link rel="stylesheet" href="loginstyles.css">
  </head>

  <body>
    <!--Main login box with appropriate classes-->
    <div id="Lbox" class="loginBox">
      <div class="loginTitle">Welcome!</div>
      <h5 id="Etext" class="emailText">EMAIL</h5>
      <div id="Einptwrap" class="emailInputWrapper">
        <input id="Einput" class="emailInput" type="email" 
        aria-label="Email" autocomplete="off" 
        spellcheck="false" maxlength="999">
      </div>
      <h5 id="Ptext" class="passwordText">PASSWORD</h5>
      <div id="Pinptwrap" class="passwordInputWrapper">
        <input id="Pinput" class="passwordInput" type="password" 
        aria-label="Password" autocomplete="off" 
        spellcheck="false" maxlength="999">
      </div>
      <button id="Lbutton" type="submit" class="loginButton" onclick="verify()">Login</button>
      <h5 class="registerText">Don't have an account?</h5>
      <a class="registerLink" href="Register.html">Register</a>
    </div>

    <!--SQL database connection scripts-->
    <script src="./sql_scripts.js"></script>

    <!--Login verification scripts-->
    <script src="./login_scripts.js"></script>

  </body>
</html>

И login_scripts.js:

function verify() {
  const electron = require('electron').remote;
  const { app, BrowserWindow, ipcMain } = require('electron').remote;
  const { ipcRenderer } = require('electron');

  //Variable declarations
  var EinputFalse = document.getElementById("Einput").value == "";
  var EinputTrue = document.getElementById("Einput") &&
  document.getElementById("Einput").value;

  var PinputFalse = document.getElementById("Pinput").value == "";
  var PinputTrue = document.getElementById("Pinput") &&
  document.getElementById("Pinput").value;

  //Input field checks
  if (EinputFalse) {
    document.getElementById("Einptwrap").style.cssText =
    "border-color: red";
    document.getElementById("Etext").innerHTML = 
    "EMAIL - <small><i>This field is required<i><small>";
    document.getElementById("Etext").style.cssText = 
    "color: red";
  }
  if (EinputTrue) {
    document.getElementById("Einptwrap").style.cssText =
    "border-color: #282e2e";
    document.getElementById("Etext").innerHTML = 
    "EMAIL";
    document.getElementById("Etext").style.cssText =
    "color: #636d6d";
  }
  if (PinputFalse) {
    document.getElementById("Pinptwrap").style.cssText = 
    "border-color: red";
    document.getElementById("Ptext").innerHTML = 
    "PASSWORD - <small><i>This field is required<i><small>";
    document.getElementById("Ptext").style.cssText = 
    "color: red";
  }
  if (PinputTrue) {
    document.getElementById("Pinptwrap").style.cssText =
    "border-color: #282e2e";
    document.getElementById("Ptext").innerHTML = 
    "PASSWORD";
    document.getElementById("Ptext").style.cssText =
    "color: #636d6d";
  }

  //Check if both input fields are filled
  if (EinputTrue && PinputTrue) {
    var einput = document.getElementById("Einput").value;
    var einputquery = "SELECT u_email FROM userdetails WHERE u_email = ?";
    var pinput = document.getElementById("Pinput").value;
    var pinputquery = "SELECT u_password FROM userdetails WHERE u_password = ?";

    //SQL database queries
    con.query(einputquery, [einput], function(err, result, fields) {
      var eResString = JSON.stringify(result);
      var eResStringRep = eResString.replace(/[{}":]/g, "").replace("[", "").replace("]", "");
      var eResStringVar = eResStringRep.slice(7);

      if (eResStringVar == einput) {
        console.log("Query success. Result: " + eResStringVar);

      }
      else {
        console.log("Error, query unsuccessful");
      }

      con.query(pinputquery, [pinput], function(err, result, fields) {
        var pResString = JSON.stringify(result);
        var pResStringRep = pResString.replace(/[{}";]/g, "").replace("[", "").replace("]", "");
        var pResStringVar = pResStringRep.slice(11);

        if (pResStringVar == pinput) {
          console.log("Query success. Result: " + pResStringVar);

        }
        else {
          console.log("Error, query unsuccessful");
        }

        //Child window (renderer process) creation in accordance with IF statement
        if (eResStringVar == einput
        && pResStringVar == pinput) {

          child = new BrowserWindow({ 
            parent: Window, 
            modal: true, 
            show: false,
            width: 400,
            height: 600,
            title: "Messaging Service",
            center: true,
            webPreferences: {
              nodeIntegration: true,
              defaultEncoding: "UTF-8",
            } 
          })
          child.loadFile('menu.html')
          child.once('ready-to-show', () => {
            child.show()
          })

          ipcMain.on('einput-send-req', (event, arg) => {
            console.log(arg);
            child.webContents.send('einput-send-act', arg);
          });

          ipcRenderer.send('einput-send-act', eResStringVar);


        }
        else if (eResStringVar != einput) {
          document.getElementById("Einptwrap").style.cssText =
          "border-color: red";
          document.getElementById("Etext").innerHTML = 
          "EMAIL - <small><i>Email does not exist<i><small>";
          document.getElementById("Etext").style.cssText = 
          "color: red";
        }
        else if (pResStringVar != pinput) {
          document.getElementById("Pinptwrap").style.cssText = 
          "border-color: red";
          document.getElementById("Ptext").innerHTML = 
          "PASSWORD - <small><i>Password does not match<i><small>";
          document.getElementById("Ptext").style.cssText = 
          "color: red";
        }
      })
    })
  }
}

//Event listener for ENTER key
var lgnbox = document.getElementById("Lbox");
lgnbox.addEventListener("keyup", function(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
    verify();
  }
});

И menu.html, который является процессом визуализации, который будет получать нужную переменную:

<html>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' 'unsafe-eval';" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="menustyles.css">
  </head>


  <body>
    <script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="./sql_scripts.js"></script>

    <script>
      const { ipcRenderer } = require('electron');

      ipcRenderer.on('einput-send-act', (event, arg) => {
        console.log(arg);
      });

    </script>

    <script>
      $(function () {
        var socket = io('http://localhost:3000');


      });
    </script>

    <div class="menuHeader">
      <button class="settingsButton">Settings</button>
    </div>
    <ul id="users"></ul>

  </body>

</html>

Программа сравнивает входную переменную к переменной в моей базе данных SQL (используя phpMyAdmin) с помощью запроса и возвращает отредактированную и "нарезанную" переменную. В этом случае я проверяю, будет ли передана переменная электронной почты с использованием ipcMain и ipcRenderer.

Однако это не сработало, но при запуске программы также не возникает никаких ошибок. Я попытался поместить функцию ipcMain в main.js, который является основным файлом запуска Electron, и объявить дочернее окно в main.js, но это приводит к появлению множества ошибок.

Код для main.js здесь:

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

//Server setup and initialisation
const server = require('./serversetup.js').server;
const port = process.env.port || 3000;
server.run(port);

//Creating application window
function createWindow() {
  win = new BrowserWindow({
    width: 700,
    height: 800,
    backgroundColor: "#343c3c",
    center: true,
    title: "Messaging Service",
    webPreferences: {
      nodeIntegration: true,
      defaultEncoding: "UTF-8",
    }
  })
  win.once('ready-to-show', () => {
    win.show()
  })
  win.loadFile('login.html')
  win.on('closed', () => {
    win = null
  })
}

//Application startup processes
app.on('ready', () => {
  createWindow()
})
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

Я хотел бы знать, что я делаю неправильно и есть ли способ исправить эту проблему.

TL; DR Я пытаюсь передать переменную из процесса, который использует систему входа в систему (login.html), в другой процесс (menu.html), используя Electron.

1 Ответ

1 голос
/ 29 февраля 2020

Вы можете использовать электрон ip c API для связи между несколькими windows.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...