DEV Community

Cover image for Add Notifications to a 3rd party Website
Michael Salaverry
Michael Salaverry

Posted on

3

Add Notifications to a 3rd party Website

Ever had to monitor a long running process on a webpage like Jenkins? Constantly switching tabs to check if a long running task is finished is a pain, and we can ameliorate it with a small amount of code.

MDN has a great article on the notification API so I'll skip that part in this blog post. (Flavio Copes also wrote a great introduction to the Notification API) What I want to show you is how to use that API in a page.

There's a great tool called Violent Monkey which lets you add your own Javascript userscripts to run on a 3rd party website. Using a userscript, we can trigger the Notification API for almost any page event. (There's also a cool separate tool for adding your own CSS called stylus which is outside the scope of this blog).

The trick is to add an event listener or selector in Javascript for the thing you want to notify on. For example, when Jenkins finishes a build, it changes the header color from blue to green or red. We can use a CSS selector via document.querySelector() that when a classname has been added to a specific DOM node, that our script will trigger a notification.

Check out my example using the selector method:

// ==UserScript==
// @name Notify on build success
// @namespace Violentmonkey Scripts
// @match https://yourjenkins.com/blue/yourbuild/PR-*
// @grant none
// @version 1.0
// @author -
// @description 11/11/2021, 3:27:47 PM
// ==/UserScript==
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission !== "granted") {
console.warn('does not have permission to notify you on changes')
}
});
function notifyIfSucceeded() {
console.debug('checking if build succeeded')
let header = document.querySelector('#outer > div > span > div > section');
if(header?.classList.contains('BasicHeader--success')) {
console.debug('build succeeded!')
new Notification('build succeeded!')
}
else {
setTimeout(notifyIfSucceeded, 1000);
}
}
notifyIfSucceeded();

Notice that it runs in a somewhat recursive loop, with a base case that does not trigger a second alert.

Which pages do you need a notification for?

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay