简体   繁体   中英

Play sound when Tab is Active

Hello I have hear my script to play sound when Tab is not Active, how I can change this to play also when I'm on the Tab?

'document.addEventListener('chatLoaded', function(event) {
event.chat.audioControl.loadSoundFile('http://www.soundjay.com/misc/sounds/handbag-lock-4.mp3');
document.addEventListener('newMessage', function(event) {
    var chat = event.chat;
    if (!chat.isActiveTab()) {
        event.chat.audioControl.play();
    }
});

});'

Use focus() and blur() function to detect if tab is active or not. Or you can use page visibility API ( https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API )

Correct me if I'm wrong but If I got your question right and when you said "tab" you meant the browser tab, that seems pretty simple to me. All you have to do is remove the if statement, then it'll play the sound every time the event is triggered:

document.addEventListener('newMessage', function(event) {
    event.chat.audioControl.play();
});

If with "tab" what you meant was an HTML element, you can use blur and focus events to keep track of focusing state. In this case there's also solutions to check about user visibility in the browser tab, which Shota Noniashvili answer is covering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM