YouTube Live Chat Notification Sounds

Summary

בשרת מתכנתים ומפתחים בישראל - Israel Developers שותפים קוד JavaScript פשוט שמפעיל סאונד בכל פעם שנכנסת הודעה בצ'אט של YouTube. ההודעה מתארת שימוש ב-MutationObserver, URL של סאונד בדמות התראה של Discord וטיפול בחסימת autoplay בדפדפן. מתאים למי שרוצה לא לפספס הודעות בשידור חי.

Original Post

נמאס לכם להחמיץ הודעות מהצ'אט? הכנתי קוד שמפעיל סאונד כל פעם ששולחים הודעה!

(function() {
    // 1. Define the Discord notification sound
    const audioUrl = "https://www.myinstants.com/media/sounds/discord-notification.mp3";
    const notificationSound = new Audio(audioUrl);

    // 2. Find the chat container that holds the messages
    const chatContainer = document.querySelector("#items.yt-live-chat-item-list-renderer");

    if (!chatContainer) {
        console.error("Could not find the chat container. Make sure you are inspecting the YouTube chat frame/iframe!");
        return;
    }

    console.log("🎯 YouTube Chat Sound Alert Active! Listening for new messages...");

    // 3. Setup the MutationObserver to look for incoming messages
    const observer = new MutationObserver((mutationsList) => {
        for (const mutation of mutationsList) {
            // Check if nodes (elements) were added to the chat container
            if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                mutation.addedNodes.forEach((node) => {
                    // Filter out system messages (like slow mode tags) and ensure it's a real chat message
                    if (node.tagName && node.tagName.toLowerCase() === 'yt-live-chat-text-message-renderer') {

                        // Play the sound! (Catch errors if browser blocks auto-play before user interaction)
                        notificationSound.play().catch(err => {
                            console.warn("Audio playback blocked or failed. Click anywhere on the page once to allow sound.", err);
                        });

                    }
                });
            }
        }
    });

    // 4. Start observing the chat container
    observer.observe(chatContainer, { childList: true, subtree: false });
})();

The latest from מתכנתים ומפתחים בישראל - Israel Developers