V
V
vo3dooh2020-04-29 19:08:00
JavaScript
vo3dooh, 2020-04-29 19:08:00

How to create a new window in Electron?

Guys, tell me please, because I can not understand how to move forward in the development of the application. What is the point: on the server, I implemented the Rest API for registering and authorizing a user in my application. Main files code:

Server code (app.js)

const port = 3002;
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/routes');
const session = require('express-session');
const app = express();

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 }
}))

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true,
}));

routes(app)

const server = app.listen(port, (error) => {
    if (error) return console.log(`Error: ${error}`);

    console.log(`Server listening on port ${server.address().port}`);
});


Server code (routes.js)
const pool = require('../data/config');

const router = app => {

  app.get('/', function(request, response) {
  	response.sendFile(path.join(__dirname + '/index.html'));
  });

  app.post('/auth', function(request, response) {
  	var username = request.body.username;
  	var password = request.body.password;
    if (username && password) {
        pool.query('SELECT username, password FROM users WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
  			if (results.length > 0) {
  				request.session.loggedin = true;
  				request.session.username = username;
  				response.redirect('/login');
  			} else {
  				response.send('Incorrect Username and/or Password!');
    			response.end();
        	}
  		});
  	} else {
  		response.send('Please enter Username and Password!');
  		response.end();
  	}
  });

  app.get('/login', function(request, response) {
  	if (request.session.loggedin) {
  		response.send('Welcome back, ' + request.session.username + '!');
  	} else {
  		response.send('Please login to view this page!');
  	}
  	response.end();
  });

  app.post('/registration, (request, response) => {
    pool.query('INSERT INTO users SET ?', request.body, (error, result) => {
        if (error) throw error;

        response.status(201).send(`User added with ID: ${result.insertId}`);
      });
  });

}

module.exports = router;


And here is the code for the

Electron App (main.js)
const path = require('path');
const url = require('url');
const config = require('./config.js');
const {app, BrowserWindow} = require('electron');

let win;

function createWindow() {
  win = new BrowserWindow({
    width: 780,
    height: 497,
    icon: __dirname + "/img/icon.png",
    frame: false,
    hasShadow: false,
    transparent: true
  });
  
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file',
    slashes: true
  }));
  
  win.on('closed', () => {
    win = null
  });

};

app.on('ready', function () {
    setTimeout(function() {
        createWindow();
    }, 500);
});

app.on('window-all-closed', () => {
  app.quit();
})


Electron App (index.html)
<!DOCTYPE html>
<html lang="ru" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Project</title>
    <link rel="stylesheet" href="all.min.css">
  </head>
  <body>
    <div class="container" id="container">
      <div class="form-container sign-up-container">
        <form action="http://localhost:3002/registration" method="post">
          <h1>Create Account</h1>
          <input type="text" name="username" placeholder="Login" />
          <input type="email" name="email" placeholder="Email" />
          <input type="password" name="password" placeholder="Password" />
        <input type="submit" value="Registration">
        </form>
      </div>
      <div class="form-container sign-in-container">
        <form action="http://localhost:3002/auth" method="post">
          <h1>LoginIn</h1>
          <input type="text" name="username" placeholder="Login" />
          <input type="password" name="password" placeholder="Password" />
          <input type="submit" value="LoginIn">
        </form>
      </div>
    </div>
  </body>
    <script>
      require('./render.js')
    </script>
</html>


Perhaps the code is not very correct, but this is my first application and some things are not clear to me ...

Everything is clear with registration, data from forms is entered into the database. I can not understand a little how to move on in terms of authorization. From the server, I receive this message in the electronic application if the login and password match
response.send('Welcome back, ' + request.session.username + '!');

But how to move on? I just got stuck on this. In general, there are two options:
1) Redirect to another html page, or what seems more logical to me
2) Closing the current window after successful authorization and opening a new one with another html page, while the session should remain.
Tell me how to implement it, I will be immensely grateful to you for your help !!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-05-20
@karatel318

for Electron 0.35.0 and above there is ipcMain and ipcRenderer :

// In main process.
const ipcMain = require('electron').ipcMain;

// in main process, outside of app.on:
ipc.on('load-page', (event, arg) => {
    mainWindow.loadURL(arg);
});

// In renderer process (web page).
const ipc = require('electron').ipcRenderer;
ipc.send('load-page', 'file://' + __dirname + '/prefs.html');

This is about creating windows in Electron. At the expense of saving the session, unfortunately, I will not tell you.
How rich, as they say :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question