Gayatri Gayatri - 2 months ago 15
HTML Question

Developing a sticky component which will be always on top in Electron or JS

I have existing Electron based remote desktop control application which runs as a desktop app on Mac, Windows and it runs as webapp on Chrome and Firefox.

Now, I want to develop a sticky component which will be always on top, irrispective of an active window.for example a toolbar which will be always visible even if user minimizes my app and brings some other app on top.

Can someone suggest me the library or technology (e.g. Electron/ReactJS etc) using which this could be achieved ?

Thanks,
Gayatri

Answer Source

This is a quick example how I would do it. (created with electron-quick-start)

Wait for mainWindow's minimize event and create a new BrowserWindow with alwaysOnTop: true.

Docs: https://github.com/electron/electron/blob/master/docs/api/browser-window.md

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>

<body>
    Index
</body>

</html>

toolbar.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>toolbar</title>
</head>

<body>
    toolbar
</body>

</html>

renderer.js

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

const path = require('path');
const url = require('url');

let mainWindow = null;
let toolbarWindow = null;

const createWindow = () => {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    });

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }));

    mainWindow.on('closed', () => {
        mainWindow = null;
    });

    const onCloseMainWindow = (event) => {
        toolbarWindow = new BrowserWindow({
            width: 300,
            x: 20,
            y: 40,
            height: 70,
            resize: false,
            type: 'toolbar',
            alwaysOnTop: true
        })

        toolbarWindow.loadURL(url.format({
            pathname: path.join(__dirname, 'toolbar.html'),
            protocol: 'file:',
            slashes: true
        }));

        toolbarWindow.on('minimize', (event) => {
            if (mainWindow) {
                mainWindow.show();
            }
            toolbarWindow.destroy();
        });
    };

    mainWindow.on('minimize', onCloseMainWindow);
    mainWindow.on('close', onCloseMainWindow);
};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
})

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
});