Skip to content

Instantly share code, notes, and snippets.

@roman-bgonz
Created February 16, 2023 15:03
Show Gist options
  • Save roman-bgonz/b92307e4e4c50030530f9747027d711b to your computer and use it in GitHub Desktop.
Save roman-bgonz/b92307e4e4c50030530f9747027d711b to your computer and use it in GitHub Desktop.
Javascript notifications
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Javascript Notification</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<button class="notify">Notify me</button>
<script>
const notificationBtn = document.querySelector('.notify');
const requestPermission = function () {
// First, we validatw if browser supports this feature
if (!('Notification' in window))
throw new Error("Browser doesn't support Notification");
// A notification is shown
Notification.requestPermission().then((permission) => {
const notification = new Notification('Test', {
body: 'This is a test notification',
});
});
};
// A click event listener is added and created function to trigger the notification is attached
notificationBtn.addEventListener('click', requestPermission);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment