search
HomeWeb Front-endJS TutorialTIL: Block tabs and Get IP in Javascript

Welcome to the first installment of my "Today I Learned" series! Through these posts, I'll share practical insights gained during my work as an algorithm engineer, delving into the techniques I’ve implemented to address real-world challenges. I hope these lessons offer value to your projects as well.

Key Takeaways

  • Controlling Multiple Tab Instances: Preventing users from opening multiple instances of the same web application, which can drain resources and potentially crash servers.
  • Obtaining User IP Address with JavaScript: Understanding why obtaining a user’s IP address in JavaScript is a challenge due to security constraints and exploring workarounds.

To illustrate, I’ll walk through a project I worked on involving face recognition technology—specifically the steps needed to streamline processing and maintain performance across users.

Project Overview: Building a Face Recognition Web Application

TIL: Block tabs and Get IP in Javascript

In this example, the task was to create a face recognition application (Check in check out system) accessible via a web browser. The application needed to:

  1. Automatically start when the page loads.
  2. Capture the user's face, check for "liveness" (to confirm it's a real person), and then transmit the image to a server for recognition.
  3. Display the recognition result on the browser.

The application is designed with two main components:

  • Client-Side Processing: Includes face detection and liveness detection, handled in the browser.
  • Server-Side Processing: Responsible for face recognition, leveraging server resources for identity matching.

For simplicity, imagine the client detects and verifies a face before sending it to the server, where the server returns results, and the browser displays them.

The Problem: Preventing Multiple Tabs

TIL: Block tabs and Get IP in Javascript

Imagine a typical user, Alex, who recently started using a new face recognition web app to clock in and out of work. One morning, Alex decided to open the app in a few browser tabs, thinking he could speed up his check-in by testing it in multiple tabs at once.

Almost immediately, things went downhill. As each tab loaded, it independently initialized the app’s face detection and verification processes. Alex noticed his computer slowing down drastically, and eventually, the browser began to lag. Behind the scenes, these multiple tabs were each using resources to process Alex’s face, taking a big toll on his device’s performance.

But the problem didn’t end there. With each tab sending separate recognition requests to the server, the app’s server load spiked, causing delays for other users logging in at the same time. The server, overwhelmed by duplicate requests, could barely keep up, resulting in delays and missed check-ins.

To make things more confusing, each tab displayed a different, inconsistent login status. Alex quickly realized that opening the app in multiple tabs had caused unnecessary headaches for him and potential issues for the entire company.

To ensure seamless functionality and avoid unnecessary strain on both client and server resources, we needed to prevent users from opening multiple tabs with the application

The goal was to restrict users from opening more than one instance of the app at a time in their browser, primarily by detecting when other tabs with the same app are already open. Here’s how to approach this:

if (localStorage.getItem('isAppRunning') === 'true') {
    alert("The application is already open in another tab. Please close this tab.");
} else {
    // Set a flag in localStorage to indicate the app is running
    localStorage.setItem('isAppRunning', 'true');

    // Add an event listener to clear the flag when the tab is closed
    window.addEventListener('beforeunload', () => {
        localStorage.removeItem('isAppRunning');
    });

    // Main function to load models and start video if the app is not running in another tab
    (async function main() {
        try {
            const config = await loadConfig(); // Load models concurrently

            const [tinyFaceDetector, fasnet, phoneDetect] = await Promise.all([
                loadTinyFaceDetector(),
                loadFasnet(config),
                loadPhoneDetect(config),
            ]);
            Object.assign(window, { fasnet, phoneDetect, config });

            startVideo();
        } catch (err) {
            console.error('Initialization failed:', err);
        }
    })();
}

The Problem: Get user IP

In our face recognition system, the requirement has evolved to allow only authorized department-specific access. For instance, if Person A belongs to Department A, they should only be able to check in or out on devices in Department A's network, and not in Department B or any other department. Since these computers are connected via a local area network (LAN), we need a way to identify and restrict access based on the IP address of the device

TIL: Block tabs and Get IP in Javascript

When I searched online I got some info about getting the IP address. But they have a few issues

function user_location() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log( this.responseText);
    }
  };
  xhttp.open("GET", "//api.ipify.org?format=json", true);
  xhttp.send();
}

This function successfully retrieves the user’s public IP address; however, it does not provide the internal LAN IP address required for department-specific access control. Additionally, it is susceptible to masking by VPNs or firewalls.

or maybe this one

Firefox and Chrome have implemented WebRTC that allow requests to STUN servers be made that will return the local and public IP addresses for the user

But I don't wanna add more packages into my app. This complexity, combined with potential cross-browser inconsistencies, makes it less desirable.

Then I found this post

Retrieving a client ip address directly with JavaScript running in the browser is not straightforward. This is because JavaScript does not have access to the network layer where IP addresses are exposed. Moreover, for security reasons, browsers sandbox the JavaScript environment, preventing it from accessing certain system-level information, including the client's ip address.

It turns out that retrieving the IP address solely with JavaScript isn't feasible. However, there's a straightforward solution: creating an API endpoint on the server to obtain the user's IP address.

if (localStorage.getItem('isAppRunning') === 'true') {
    alert("The application is already open in another tab. Please close this tab.");
} else {
    // Set a flag in localStorage to indicate the app is running
    localStorage.setItem('isAppRunning', 'true');

    // Add an event listener to clear the flag when the tab is closed
    window.addEventListener('beforeunload', () => {
        localStorage.removeItem('isAppRunning');
    });

    // Main function to load models and start video if the app is not running in another tab
    (async function main() {
        try {
            const config = await loadConfig(); // Load models concurrently

            const [tinyFaceDetector, fasnet, phoneDetect] = await Promise.all([
                loadTinyFaceDetector(),
                loadFasnet(config),
                loadPhoneDetect(config),
            ]);
            Object.assign(window, { fasnet, phoneDetect, config });

            startVideo();
        } catch (err) {
            console.error('Initialization failed:', err);
        }
    })();
}
  • When a client makes a request, Flask automatically populates the request object with various headers and connection details.

  • First, the code checks the X-Forwarded-For header with client_ip = request.headers.get('X-Forwarded-For').

  • Purpose: This header is commonly set by proxies or load balancers to preserve the original client IP address. If the request passed through a proxy or load balancer, the client’s actual IP address should appear in this header.

  • If the X-Forwarded-For header is found, client_ip is set to its value.

  • If the X-Forwarded-For header is missing (e.g., if the client connects directly without a proxy), the code uses request.remote_addr to get the IP address directly from the client.

Summary

In this post, I share my experiences tackling real-world challenges in developing a web-based face recognition app. Here are two key problems we solved:

  • Preventing Multiple Tab Instances: To stop users from opening the app in multiple browser tabs, we use localStorage to track whether the app is already open. This prevents redundant face-detection processes that strain both client and server resources.

  • Retrieving User IP Address: Since JavaScript cannot directly access a device’s LAN IP due to security limitations, we set up an API endpoint on the server to obtain the IP from request headers. This approach ensures department-specific access control for authorized devices only.

The above is the detailed content of TIL: Block tabs and Get IP in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version