Skip to content

Instantly share code, notes, and snippets.

@ddrscott
Created June 3, 2021 18:47
Show Gist options
  • Save ddrscott/6b892b133a157efb94328a9f8566247d to your computer and use it in GitHub Desktop.
Save ddrscott/6b892b133a157efb94328a9f8566247d to your computer and use it in GitHub Desktop.
Helper to watch for DOM elements getting added and saying the contents.
function sayLastChild(selector) {
// Select the node that will be observed for mutations
const targetNode = document.querySelector(selector);
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
let mutation = mutationsList.pop();
if (mutation.type === 'childList') {
console.log("saying:", mutation.target.innerText);
window.setTimeout(() => {
let ut = new SpeechSynthesisUtterance(mutation.target.innerText);
speechSynthesis.speak(ut);
}, 0);
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
}
@ddrscott
Copy link
Author

ddrscott commented Jun 3, 2021

Example delaying the mutation observation for 2 seconds and matching class starting with something:

(function() {
    'use strict';
    window.setTimeout(() => {
        sayLastChild('div[class^="styles_messageList"]');
    }, 2000);
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment