4

I have a scenario where I have to produce a sound when a specific error message exists out of many error messages from the apex class.

I built a JavaScript function for the sound.

    <audio id="audio" src="http://www.soundjay.com/button/beep-07.wav" autostart="false" ></audio>

       <apex:pagemessages>

    <apex:actionsupport event = 'onchange' onsubmit = 'PlaySound()' />



    </apex:pagemessages>

​    <script>

    function PlaySound() {

          var sound = document.getElementById("audio");

          sound.play()

      }

    </script>

But how do I call "PlaySound()" when there is an error message. I tried using actionsupport for this, but it didn't work. I'm not sure whether actionsupport executes on error message on page or not.

How do I get to call the function when error exists?

3

Try using a snippet which is executed only when there are messages on the page of a given severity. As long as this apex:outputPanel is re-rendered, so it has the most up-to-date values from the controller, you should get a sound played when an ApexPages.Message is on the page with the given severity.

<apex:page controller="TestController">
    <script>
        function PlaySound() {
            console.log('Sound played!');
        }
    </script>

    <apex:form >

        <apex:pageMessages />

        <apex:outputPanel rendered="{!ErrorMessagesOnPage}" id="soundNotice">
            <script>
                (function() {
                    PlaySound();
                })();
            </script>
        </apex:outputPanel>

        <apex:commandButton action="{!RefreshPage}" value="Refresh Page" />

    </apex:form>
</apex:page>

Controller:

public class TestController {

    public TestController() {}

    public Boolean ErrorMessagesOnPage {
        get {
            return ApexPages.hasMessages(ApexPages.Severity.ERROR);
        }
    }

    public PageReference RefreshPage() {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Something went wrong!'));

        return null;
    }

}
| improve this answer | |
  • I tried it and it's throwing a javascript error " Uncaught ReferenceError: PlaySound is not defined" from chrome browser debug console – Anurag Aug 8 '16 at 16:16
  • I've added a more complete example. As long as your page is set up similarly, you shouldn't have any issues. – battery.cord Aug 8 '16 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.