How to send notifications in JavaScript(less than 10 lines of code)

Disclaimer: What the title means by ‘sending notifications in less than 10 lines of code is referring to the number of lines of JavaScript code.

If you prefer a video guide:

Video Explanation

You know those annoying notifications popping up at the least-wanted time? Today, I’ll teach you how to make a desktop/mobile responsive push notification with less than 10 lines of Javascript.

Step 1 (Setting up)

Open up the Visual studio code, if you have not installed it yet, you can install it below:
https://code.visualstudio.com/

After that, open a blank folder(file>open folder), and in that folder, add a file called index.html.

Adding file

Step 2 (Coding)

Copy this code into your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notification Test</title>
</head>
<body>
    <button id="btn">Test</button>
    <script>
        document.getElementById('btn').onclick = notify
        function notify(){
            Notification.requestPermission().then(permission => {
                if (permission === "granted"){
                    new Notification("Test Notification", {
                        body: "More Text",
                    })
                }
            })
        }
    </script>
</body>
</html>

Step 3 (Running the code)

Select the extension button from the sidebar, then search live server.

Sidebar

Select the first option and install it. Now open your index.html file, right-click it, and select open with a live server. A window should pop up, now just click the test button. Remember to enable notifications by clicking the lock button in your browser.

Conclusion

I hope you enjoyed this tutorial! If it was too quick for you, make sure to subscribe by scrolling to the very bottom, a more detailed version is coming out!