Showing posts with label Client-Side. Show all posts
Showing posts with label Client-Side. Show all posts

Sunday, September 15, 2024

Implementing Clickjacking Defense Techniques in JavaScript

 

Implementing Clickjacking Defense Techniques in JavaScript

https://www.nilebits.com/blog/2024/09/clickjacking-techniques-javascript/

The emergence of sophisticated assaults like clickjacking has made security a primary issue in today's online world. By deceiving consumers into clicking on something that differs from what they initially see, attackers deploy a nefarious method called "clickjacking," which can have disastrous results. Attacks of this kind have the potential to trick people into downloading malware, sending private information, or even doing things they didn't mean to, like buying anything. In order to protect against these kinds of assaults, JavaScript is an essential component of dynamic web applications.

In this blog post, we will dive deep into how clickjacking attacks work, why they are so dangerous, and how you can implement clickjacking defense techniques in JavaScript. We will provide practical code examples and strategies to help secure your web applications and prevent these malicious attacks.

Understanding Clickjacking Attacks

Clickjacking is a type of attack where a malicious website embeds another website, typically by using an HTML <iframe>, and overlays it with invisible or misleading elements, effectively "hijacking" the user's clicks. When the user interacts with the embedded page, they believe they are clicking a button or a link on the visible site, but they are actually interacting with the hidden embedded site.

Here’s a basic example of how an attacker might perform a clickjacking attack:

<!DOCTYPE html>
<html>
<head>
    <title>Malicious Page</title>
    <style>
        iframe {
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0.01; /* Make the iframe nearly invisible */
            width: 100%;
            height: 100%;
            z-index: 999;
        }
    </style>
</head>
<body>
    <h1>Click the button to win a prize!</h1>
    <button>Claim Prize</button>
    <iframe src="https://www.vulnerablewebsite.com"></iframe> <!-- Embedded target page -->
</body>
</html>

In the code above, the attacker’s page appears as a normal webpage, but an invisible iframe that loads the target page is overlaid on top of it. Users think they’re interacting with the malicious page, but they’re really clicking on elements within the iframe.

Why Clickjacking is Dangerous

Clickjacking can lead to serious consequences, including:

  • Unintentional purchases: Users may click on hidden "Buy" buttons, resulting in unwanted transactions.
  • Account compromise: Attackers can trick users into changing their settings or submitting sensitive data on websites they trust.
  • Download of malware: Clickjacking can be used to initiate downloads of malicious files, infecting users' devices.
  • Loss of control over social media: Some attacks involve tricking users into liking or sharing content on social media platforms.

These attacks are particularly dangerous because users typically have no idea they've been compromised until it's too late.

Defending Against Clickjacking in JavaScript

Now that we understand how clickjacking works, let’s explore various defense techniques you can implement in JavaScript.

1. Using X-Frame-Options Header

The X-Frame-Options HTTP header is one of the simplest and most effective ways to prevent your web pages from being embedded in iframes on other websites. This header instructs the browser whether the site can be embedded within an iframe.

There are three main options for the X-Frame-Options header:

  • DENY: Prevents the page from being displayed in an iframe entirely.
  • SAMEORIGIN: Allows the page to be embedded only if the request originates from the same domain.
  • ALLOW-FROM: Allows the page to be embedded only by a specific, trusted domain.

Here’s how you can set this header using JavaScript in Node.js:

const express = require('express');
const helmet = require('helmet');

const app = express();

// Use helmet to set X-Frame-Options header
app.use(helmet.frameguard({ action: 'deny' }));

app.get('/', (req, res) => {
    res.send('Clickjacking prevention with X-Frame-Options');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

In this example, the helmet.frameguard() middleware ensures that the X-Frame-Options header is set to DENY for all responses, effectively preventing clickjacking by disallowing iframe embedding.

2. Content Security Policy (CSP)

Another effective defense mechanism is using the Content-Security-Policy (CSP) header. The CSP header provides more fine-grained control over how and where your content can be embedded.

To prevent clickjacking, you can include the frame-ancestors directive in your CSP header. This directive allows you to specify which domains are allowed to embed your site.

Example CSP header:

Content-Security-Policy: frame-ancestors 'self';

This policy ensures that only the same origin ('self') can embed the page in an iframe, effectively preventing other websites from doing so.

Here’s how to implement CSP in a Node.js application:

const express = require('express');
const app = express();

app.use((req, res, next) => {
    res.setHeader("Content-Security-Policy", "frame-ancestors 'self'");
    next();
});

app.get('/', (req, res) => {
    res.send('CSP frame-ancestors directive in action!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

3. JavaScript Frame Busting Techniques

Although relying on headers like X-Frame-Options and CSP is generally more reliable, you can also implement frame busting using JavaScript. Frame busting scripts detect when your page is being embedded in an iframe and force it to break out of the iframe.

Here’s a simple JavaScript snippet to detect and prevent iframe embedding:

if (window.top !== window.self) {
    // The page is embedded in an iframe, so redirect it
    window.top.location = window.self.location;
}

This code checks if the current window is being loaded within an iframe (window.top !== window.self). If it is, it redirects the parent frame (window.top) to the current location of the iframe (window.self), effectively breaking out of the iframe.

This is a basic technique and can be circumvented by advanced attackers, so it should be used as a secondary defense mechanism in conjunction with headers like X-Frame-Options and CSP.

4. Double-Checking Click Actions with JavaScript

Another defensive technique is adding confirmation dialogs for critical actions that could be exploited in a clickjacking attack. By requiring users to confirm their actions, you can reduce the risk of unauthorized clicks.

Here’s an example of adding a confirmation dialog to a button click event:

<button id="deleteButton">Delete Account</button>

<script>
document.getElementById('deleteButton').addEventListener('click', function(event) {
    if (!confirm('Are you sure you want to delete your account?')) {
        event.preventDefault(); // Cancel the action if the user clicks "Cancel"
    }
});
</script>

In this example, when the user clicks the "Delete Account" button, a confirmation dialog appears. If the user cancels, the action is prevented.

5. Implementing Sandbox Attributes for Embedded Content

When embedding content on your own site, you can use the sandbox attribute on iframes to restrict the functionality of the embedded content. This is useful when embedding untrusted third-party content, as it limits what the embedded content can do.

For example:

<iframe src="https://thirdpartywebsite.com" sandbox="allow-scripts allow-same-origin"></iframe>

The sandbox attribute applies restrictions on the iframe, such as disabling forms, scripts, and preventing the iframe from navigating the parent page. You can selectively allow certain functionalities by adding values like allow-scripts or allow-same-origin.

Conclusion: Strengthening Clickjacking Defenses

Clickjacking is a serious security risk that web developers must address to protect users and data. By implementing defense techniques such as setting the X-Frame-Options and Content-Security-Policy headers, using JavaScript frame busting techniques, and adding user confirmation dialogs for critical actions, you can significantly reduce the risk of clickjacking attacks on your web applications.

It’s essential to layer these defense mechanisms to ensure comprehensive protection, as no single method is foolproof on its own. By combining multiple strategies, you can make your web applications more resilient to clickjacking and other forms of attacks.

By staying informed and vigilant, you can protect your users and their data from the dangers of clickjacking, ensuring a more secure browsing experience.

https://www.nilebits.com/blog/2024/09/clickjacking-techniques-javascript/

Thursday, August 8, 2024

Boosting Your Next.js App with SEO: Implementing Static & Dynamic Metadata

 

Boosting Your Next.js App with SEO: Implementing Static & Dynamic Metadata

https://www.nilebits.com/blog/2024/08/boosting-your-nextjs-app-with-seo/

It is imperative that your Next.js application is search engine optimized in the cutthroat online environment of today. Though Next.js provides powerful server-side rendering and static site creation tools, the real strength is in how you use and maintain both static and dynamic information to improve your app's search engine ranking. With the help of this thorough tutorial, you will be able to optimize your Next.js application and increase its search engine ranking and reach by using both static and dynamic information.

Understanding Metadata in Next.js

Understanding what metadata is and why it's important for SEO is necessary before delving into the code. Search engines index and rank your web pages based on metadata, which includes things like the title, description, and keywords. The visibility of your website can be considerably increased with well-managed metadata.

Setting Up a Next.js Project

Let's start by creating a new Next.js project. If you haven't already set up Next.js, follow these steps to get started:

npx create-next-app my-seo-app
cd my-seo-app
npm run dev

This will create a basic Next.js application that we will use to implement SEO best practices.

Implementing Static Metadata

Static metadata is content that doesn't change and is set at the build time. In Next.js , static metadata can be implemented using the <Head> component. Here's an example of how to add static metadata to a page:

import Head from 'next/head';

export default function Home() {
  return (
    <>
      <Head>
        <title>My SEO-Optimized Next.js App</title>
        <meta name="description" content="This is a sample application optimized for SEO using Next.js." />
        <meta name="keywords" content="Next.js, SEO, Static Metadata" />
        <meta name="robots" content="index, follow" />
      </Head>
      <h1>Welcome to My SEO-Optimized Next.js App</h1>
      <p>This is the homepage of your SEO-friendly Next.js application.</p>
    </>
  );
}

Implementing Dynamic Metadata

Dynamic metadata, on the other hand, changes based on the content or user interaction. This is particularly useful for pages like blogs or product listings, where each page might have different metadata. Next.js makes it easy to generate dynamic metadata by fetching data during the server-side rendering process.

Here’s how you can implement dynamic metadata in a Next.js app:

import Head from 'next/head';

export async function getServerSideProps(context) {
  const { slug } = context.params;
  const res = await fetch(`https://api.example.com/posts/${slug}`);
  const post = await res.json();

  return {
    props: {
      post,
    },
  };
}

export default function BlogPost({ post }) {
  return (
    <>
      <Head>
        <title>{post.title} - My Blog</title>
        <meta name="description" content={post.excerpt} />
        <meta name="keywords" content={post.keywords.join(', ')} />
        <meta name="robots" content="index, follow" />
      </Head>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </>
  );
}

Combining Static and Dynamic Metadata

In many cases, you might want to combine both static and dynamic metadata. For instance, you could have a static base title for your site but dynamically generate other metadata based on the content. Here's an example:

import Head from 'next/head';

export async function getStaticProps() {
  const res = await fetch('https://api.example.com/homepage');
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

export default function Home({ data }) {
  return (
    <>
      <Head>
        <title>{data.title} - My SEO-Optimized Next.js App</title>
        <meta name="description" content={data.description} />
        <meta name="keywords" content={data.keywords.join(', ')} />
      </Head>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </>
  );
}

Advanced SEO Techniques with Next.js

Beyond basic metadata management, Next.js offers advanced features to enhance your SEO strategy. Here are a few techniques:

  1. Canonical Tags: Prevent duplicate content issues by specifying canonical URLs for your pages.
<Head>
  <link rel="canonical" href="https://example.com/your-page" />
</Head>
  1. Open Graph and Twitter Cards: Improve social media sharing by adding Open Graph and Twitter Card metadata.
<Head>
  <meta property="og:title" content="My SEO-Optimized Next.js App" />
  <meta property="og:description" content="This is a sample application optimized for SEO using Next.js." />
  <meta property="og:image" content="https://example.com/og-image.jpg" />
  <meta property="og:url" content="https://example.com" />
  <meta name="twitter:card" content="summary_large_image" />
</Head>
  1. Structured Data: Implement JSON-LD structured data to help search engines better understand your content.
<Head>
  <script type="application/ld+json">
    {`
      {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "url": "https://example.com",
        "name": "My SEO-Optimized Next.js App",
        "potentialAction": {
          "@type": "SearchAction",
          "target": "https://example.com/search?q={search_term_string}",
          "query-input": "required name=search_term_string"
        }
      }
    `}
  </script>
</Head>

Optimizing Performance for SEO

Performance is a critical factor in SEO. Search engines like Google prioritize fast-loading websites, and Next.js provides several features to enhance performance:

  • Image Optimization: Use the next/image component for optimized image loading.
  • Code Splitting: Next.js automatically splits your code, loading only what’s necessary.
  • Static Site Generation (SSG): Where possible, use SSG to serve pre-rendered pages for faster load times.
import Image from 'next/image';

export default function Home() {
  return (
    <>
      <Head>
        <title>Optimized Images in Next.js</title>
      </Head>
      <h1>Optimized Images</h1>
      <Image
        src="/images/sample.jpg"
        alt="Sample Image"
        width={500}
        height={500}
      />
    </>
  );
}

Conclusion

Implementing SEO in your Next.js app is not just about adding meta tags. It involves a holistic approach, combining static and dynamic metadata, optimizing performance, and leveraging advanced features like structured data and Open Graph. By following this guide, you’ll be well on your way to ensuring your Next.js application is not only fast and functional but also ranks well on search engines.

References:



https://www.nilebits.com/blog/2024/08/boosting-your-nextjs-app-with-seo/

Tuesday, August 6, 2024

10 Amazing Things You Can Do With Simple JavaScript

 

10 Amazing Things You Can Do With Simple JavaScript

https://www.nilebits.com/blog/2024/08/10-things-you-can-do-with-javascript/

JavaScript is a fairly flexible language that can be used to create everything from straightforward server-side systems to intricate online apps. Both inexperienced and seasoned developers love it for its versatility and simplicity of usage. This post will go over 10 incredible things you can do with basic JavaScript, along with code snippets and resources to help you learn more.

1. Create Interactive Web Pages

JavaScript is essential for adding interactivity to web pages. You can create dynamic content, handle user events, and update the DOM without reloading the page.

Example: Toggle Dark Mode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode Toggle</title>
    <style>
        body {
            transition: background-color 0.3s, color 0.3s;
        }
        .dark-mode {
            background-color: #121212;
            color: #ffffff;
        }
    </style>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <button id="toggle-dark-mode">Toggle Dark Mode</button>
    <script>
        const button = document.getElementById('toggle-dark-mode');
        button.addEventListener('click', () => {
            document.body.classList.toggle('dark-mode');
        });
    </script>
</body>
</html>

References:

2. Build Simple Games

JavaScript can be used to create engaging games directly in the browser. With the HTML5 canvas element, you can draw graphics and animate objects.

Example: Basic Snake Game

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <style>
        canvas {
            display: block;
            margin: auto;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const grid = 20;
        let snake = [{ x: 160, y: 160 }];
        let direction = 'right';
        let food = { x: 200, y: 200 };

        function update() {
            const head = { ...snake[0] };
            switch (direction) {
                case 'up': head.y -= grid; break;
                case 'down': head.y += grid; break;
                case 'left': head.x -= grid; break;
                case 'right': head.x += grid; break;
            }
            snake.unshift(head);
            if (head.x === food.x && head.y === food.y) {
                food.x = Math.floor(Math.random() * canvas.width / grid) * grid;
                food.y = Math.floor(Math.random() * canvas.height / grid) * grid;
            } else {
                snake.pop();
            }
        }

        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'green';
            snake.forEach(segment => ctx.fillRect(segment.x, segment.y, grid, grid));
            ctx.fillStyle = 'red';
            ctx.fillRect(food.x, food.y, grid, grid);
        }

        function loop() {
            update();
            draw();
            setTimeout(loop, 100);
        }

        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp': direction = 'up'; break;
                case 'ArrowDown': direction = 'down'; break;
                case 'ArrowLeft': direction = 'left'; break;
                case 'ArrowRight': direction = 'right'; break;
            }
        });

        loop();
    </script>
</body>
</html>

References:

3. Fetch and Display Data from APIs

JavaScript makes it easy to fetch data from APIs and display it dynamically on your web pages. This is especially useful for creating interactive dashboards and real-time applications.

Example: Display Weather Data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <h1>Weather App</h1>
    <input type="text" id="city" placeholder="Enter city">
    <button id="getWeather">Get Weather</button>
    <div id="weather"></div>
    <script>
        document.getElementById('getWeather').addEventListener('click', () => {
            const city = document.getElementById('city').value;
            fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`)
                .then(response => response.json())
                .then(data => {
                    const weatherDiv = document.getElementById('weather');
                    weatherDiv.innerHTML = `
                        <h2>${data.name}</h2>
                        <p>${data.weather[0].description}</p>
                        <p>Temperature: ${(data.main.temp - 273.15).toFixed(2)} °C</p>
                    `;
                })
                .catch(error => console.error('Error fetching data:', error));
        });
    </script>
</body>
</html>

References:

4. Form Validation

Client-side form validation can be easily handled with JavaScript, providing immediate feedback to users and reducing the need for server-side validation.

Example: Simple Form Validation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation</title>
</head>
<body>
    <form id="myForm">
        <label for="username">Username:</label>
        <input type="text" id="username" required>
        <span id="usernameError" style="color: red;"></span>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" required>
        <span id="emailError" style="color: red;"></span>
        <br>
        <button type="submit">Submit</button>
    </form>
    <script>
        document.getElementById('myForm').addEventListener('submit', function (e) {
            e.preventDefault();
            let valid = true;
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;

            if (username.length < 5) {
                valid = false;
                document.getElementById('usernameError').textContent = 'Username must be at least 5 characters';
            } else {
                document.getElementById('usernameError').textContent = '';
            }

            const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
            if (!emailPattern.test(email)) {
                valid = false;
                document.getElementById('emailError').textContent = 'Invalid email address';
            } else {
                document.getElementById('emailError').textContent = '';
            }

            if (valid) {
                alert('Form submitted successfully!');
            }
        });
    </script>
</body>
</html>

References:

5. Create Animations

JavaScript, along with CSS, allows you to create smooth animations on your web pages. This can be used to enhance user experience and make your site more engaging.

Example: Fade In Effect

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fade In Effect</title>
    <style>
        #fadeInElement {
            opacity: 0;
            transition: opacity 2s;
        }
        .visible {
            opacity: 1;
        }
    </style>
</head>
<body>
    <h1>Fade In Effect</h1>
    <div id="fadeInElement">Hello, World!</div>
    <button id="fadeInButton">Fade In</button>
    <script>
        document.getElementById('fadeInButton').addEventListener('

click', () => {
            document.getElementById('fadeInElement').classList.add('visible');
        });
    </script>
</body>
</html>

References:

6. Build Single Page Applications (SPAs)

JavaScript frameworks like React, Angular, and Vue allow you to build single-page applications that provide a seamless user experience.

Example: Simple SPA with Vanilla JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple SPA</title>
    <style>
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <nav>
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
    </nav>
    <div id="content"></div>
    <script>
        const routes = {
            home: '<h1>Home Page</h1><p>Welcome to the home page.</p>',
            about: '<h1>About Page</h1><p>This is the about page.</p>',
            contact: '<h1>Contact Page</h1><p>Get in touch through the contact page.</p>'
        };

        function navigate() {
            const hash = window.location.hash.substring(1);
            document.getElementById('content').innerHTML = routes[hash] || routes.home;
        }

        window.addEventListener('hashchange', navigate);
        navigate();
    </script>
</body>
</html>

References:

7. Enhance Accessibility

JavaScript can be used to improve the accessibility of your web applications, ensuring they are usable by everyone, including people with disabilities.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Skip to Content</title>
    <style>
        #mainContent {
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <a href="#mainContent" id="skipToContent">Skip to Content</a>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
    <main id="mainContent">
        <h1>Main Content</h1>
        <p>This is the main content of the page.</p>
    </main>
    <script>
        document.getElementById('skipToContent').addEventListener('click', function (e) {
            e.preventDefault();
            document.getElementById('mainContent').focus();
        });
    </script>
</body>
</html>

References:

8. Create Browser Extensions

JavaScript can be used to develop browser extensions that enhance the functionality of your browser, automate tasks, and integrate with other services.

Example: Simple Chrome Extension

Create a manifest.json file:

{
    "manifest_version": 2,
    "name": "Hello World Extension",
    "version": "1.0",
    "description": "A simple hello world Chrome extension",
    "browser_action": {
        "default_popup": "popup.html"
    }
}

Create a popup.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <button id="clickMe">Click Me</button>
    <script>
        document.getElementById('clickMe').addEventListener('click', () => {
            alert('Hello from your Chrome Extension!');
        });
    </script>
</body>
</html>

References:

9. Automate Tasks with Node.js

JavaScript can also be used on the server-side with Node.js to automate repetitive tasks, such as file manipulation, web scraping, and data processing.

Example: Read and Write Files

Create a file named app.js:

const fs = require('fs');

const content = 'Hello, World!';
fs.writeFile('hello.txt', content, (err) => {
    if (err) throw err;
    console.log('File written successfully');

    fs.readFile('hello.txt', 'utf8', (err, data) => {
        if (err) throw err;
        console.log('File content:', data);
    });
});

Run the script with Node.js:

node app.js

References:

10. Implement Machine Learning

With libraries like TensorFlow.js, you can implement machine learning models directly in the browser using JavaScript.

Example: Simple Image Classification

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Classification</title>
</head>
<body>
    <h1>Image Classification</h1>
    <input type="file" id="imageUpload" accept="image/*">
    <div id="result"></div>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
    <script>
        const imageUpload = document.getElementById('imageUpload');
        const result = document.getElementById('result');

        imageUpload.addEventListener('change', async () => {
            const file = imageUpload.files[0];
            const img = new Image();
            img.src = URL.createObjectURL(file);

            img.onload = async () => {
                const model = await mobilenet.load();
                const predictions = await model.classify(img);
                result.innerHTML = predictions.map(p => `${p.className}: ${p.probability.toFixed(2)}`).join('<br>');
            };
        });
    </script>
</body>
</html>

References:

Conclusion

There are many uses for JavaScript, making it a versatile and potent language. The possibilities are unlimited, ranging from developing single-page applications and automating processes with Node.js to making simple games and interactive web pages. You may begin exploring these incredible things you can accomplish with basic JavaScript by using the examples and resources provided. Have fun with coding!

Additional References:


https://www.nilebits.com/blog/2024/08/10-things-you-can-do-with-javascript/