Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stephancill/70dcab505cb4a36e8302561f38e8dea4 to your computer and use it in GitHub Desktop.
Save stephancill/70dcab505cb4a36e8302561f38e8dea4 to your computer and use it in GitHub Desktop.
A Tampermonkey userscript that plays a sound when the content of an element found by a user-provided XPath changes. The script is activated using the Ctrl+Shift+X key combination.
// ==UserScript==
// @name Play Sound on Element Change
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Plays a sound when the content of an element with a specific ID changes.
// @author stephancill
// @match *://*/*
// @grant none
// ==/UserScript==
(function () {
'use strict';
const soundUrl = 'https://drive.google.com/uc?id=1n_Wbf6uF2VRoxjyZvtqCtW0Mnxxep2LL';
// Function to play a sound when the content of an element found by XPath changes
function playSoundOnContentChange(elementXPath, soundUrl) {
const elementSnapshot = document.evaluate(elementXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
const targetNode = elementSnapshot.singleNodeValue;
if (!targetNode) {
console.error(`Element with XPath "${elementXPath}" not found.`);
return;
}
const audio = new Audio(soundUrl);
const observerConfig = {
childList: true,
subtree: true,
characterData: true
};
const observerCallback = (mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList' || mutation.type === 'characterData') {
audio.play();
break;
}
}
};
const observer = new MutationObserver(observerCallback);
observer.observe(targetNode, observerConfig);
}
function activateScript() {
// Prompt the user to enter the element XPath
const userInputXPath = prompt('Please enter the XPath of the element you want to watch:');
if (userInputXPath) {
// Call the function with the user input XPath and sound URL
playSoundOnContentChange(userInputXPath, soundUrl);
} else {
console.log('No XPath provided. The script will not watch any element.');
}
}
// Listen for the Ctrl+Shift+X key combination
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.shiftKey && event.code === 'KeyX') {
activateScript();
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment