1

I was just trying code in Tampermonkey that makes a sound when a type of message appears in a chat.

The problem is that this script works only on the first message and I want to make it work every time.

I have been looking through internet and I found that maybe is because something called 'iFrames'??

The script:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Sound when chat message
// @author       You
// @include      *
// @grant        none
// ==/UserScript==

var exist = false;
var notified = false;
mCoinSound = new Audio("https://dl.dropbox.com/u/7079101/coin.mp3");

setInterval(getRain, 2000);

function getRain() {
    var rain = document.getElementsByClassName('rain-message');
    exist = rain.length === 0 ? false : true;
    notified = (exist && notified);

    if (exist && !notified) {
        mCoinSound.play();
        notified = true;
    }
}
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Prodx9
  • 13
  • 3

1 Answers1

0

Since you want to play the sound once for each new rain-message node, a global state boolean like notified won't work.

You need mark each node individually. There are a variety of ways to do that, but I'm going to show how to do it using waitForKeyElements() -- since you also need to wait for AJAX'd nodes and waitForKeyElements marks nodes automatically.

The next thing is avoiding playing the sound multiple times a second. I'll use a "debounce" function for that.

Finally, don't use @include *.

Putting it all together, this script should work on Tampermonkey:

// ==UserScript==
// @name     _Play Sound on new chat message
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

let mCoinSound = new soundObj ('https://dl.dropbox.com/u/7079101/coin.mp3');

waitForKeyElements (".rain-message", playSound);

function playSound (jNode) {
    mCoinSound.playDbnc ();
}

function soundObj (audioURL) {
    let dbncTimer   = null;
    let audioObj    = new Audio(audioURL);

    this.playDbnc = function () { // "Debounce" function
        if (dbncTimer)  return;

        dbncTimer = setTimeout (resetTimer, 1111);
        audioObj.play ();
    };

    function resetTimer () {
        clearTimeout (dbncTimer);
        dbncTimer = null;
    }
}




Firefox has issues playing sounds without user interaction and needs to be "primed" with a manual click.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295