Search code examples
htmlnode.jssocket.ioscreen-size

Lightest way to set a client screen size validation in node.js before sending web app files?


I code a web app with node.js and socket.io. I dont want clients with a device screen smaller than 500px*500px to load the game. I want to verify client screen size server side, then send heavy game files or just a little html caution if the device screen isn't large enough. I try to avoid cookies. Is this possible?

Thanks


Solution

  • in the server:

    socket.emit('screen');
    socket.on('size', data => {
       let width = data.width,
           height = data.height;         
       //some code here
    });
    

    in the client (using jQuery):

    socket.on('screen', () => {
        let width = $(window).width(),   
            height = $(window).height(); 
        socket.emit('size', {width, height});
    });
    

    If you don't use jQuery you can send window.innerWidth and window.innerHeight respectively.

    You can do easily it at the client side. Have a look at the simple example:

    server.js

    const express = require('express');
    const app = express();
    
    app.get('/', (req,res) => {
        res.sendFile(__dirname + '/hello.html');
    });
    app.get('/small', (req,res) => {
        res.sendFile(__dirname + '/small.html');
    });
    app.get('/game', (req,res) => {
        res.sendFile(__dirname + '/game.html');
    });
    
    app.listen(3000);
    

    hello.html

    <html>
    <body>
        <h1>Hello</h1>
        <script>
            if (window.innerWidth < 500 || window.innerHeight < 500) {
                window.location.assign('small');
            } else {
                window.location.assign('game');
            }
        </script>
    </body>
    </html>
    

    small.html

    <html>
    <body>
        <h1>Small screen :-(</h1>
    </body>
    </html>
    

    game.html

    <html>
    <body>
        <h1>Loading The Game</h1>
    </body>
    </html>