2017-03-10 50 views
1

我只是在尝试Tampermonkey中的代码,当聊天中出现某种类型的消息时发出声音。Tampermonkey脚本只能在第一个新节点上工作

问题是,此脚本只适用于第一条消息,我希望每次都能使其工作。

我一直在寻找通过互联网,我发现可能是因为一些叫'iFrames'?

脚本:

// ==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; 
    } 
} 
+0

你认为'setInterval'在这里做什么? – jmargolisvt

+0

@jmargolisvt 我已经使用它来重复代码,并且如果消息已经出现,每2秒检查一次 – Prodx9

回答

0

既然你想一次播放的声音为每个新rain-message节点,全局状态布尔像notified将无法​​正常工作。

您需要分别标记每个节点。有很多种方法可以做到这一点,但是我将使用waitForKeyElements()来演示如何使用它 - 因为您还需要等待AJAX​​的节点,并且waitForKeyElements会自动标记节点。

接下来就是避免每秒多次播放声音。我将使用“去抖”功能。最后,不要使用@include *

把它放在一起,这个脚本应该在Tampermonkey &Dagger上工作;

// ==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在没有用户交互的情况下会播放声音,需要通过手动点击进行“启动”。

+0

工作!太好了! – Prodx9

+0

不客气!乐意效劳。 –

相关问题