ECMAScript in VoiceXML

VoiceXML supports the use of ECMAScript for client-side computation and object manipulation. To include scripting language code in your VoiceXML applications, you must use the VoiceXML <script> element. Keep in mind, however, that many VoiceXML attributes also accept ECMAScript expressions as attribute values. See VoiceXML elements for attribute details.

This sample demonstrates usage of the <script> element. The code enclosed within the <script> element allows the VoiceXML application to retrieve local time information at runtime.

<?xml version="1.0"?>
<!DOCTYPE vxml PUBLIC "-//Nuance/DTD VoiceXML 2.0//EN"
"http://voicexml.nuance.com/dtd/nuancevoicexml-2-0.dtd" >
<vxml version="2.0">
...
   <script> 
        var d = new Date(); 
        var hours = d.getHours(); 
        var minutes = d.getMinutes(); 
        var seconds = d.getSeconds(); 
   </script> 
   <form> 
     <block> 
        The time is <value expr="hours"/> hours,
        <value expr="minutes"/> minutes, and
        <value expr="seconds"/> seconds.
     </block> 
   </form>
...
</vxml> 

Note that in VoiceXML, all variables must be declared before use. This is different than in standard ECMAScript. Therefore, to ensure the validity of your code, remember to always declare variables before using them.

Boolean values in conditions

In Voice Platform, a Boolean value appearing in a condition does not take single quotes. If you do put quotes around a Boolean value it is treated as a string, so the condition will always evaluate to Boolean false.

Escape characters

Certain characters must be escaped whenever you incorporate ECMAScript code (via the <script> element) or ECMAScript expressions (via attribute values) in your VoiceXML applications.

This table lists the characters you must escape.

Character

Escape sequence

In <script> element

In attribute value

Example

<

&lt;

ü

ü

<value expr="5&lt;10"/>

>

&gt;

ü

ü

<value expr="10&gt;5"/>

&

&amp;

ü

ü

<if cond="hours &gt; 2 &amp;&amp; hours &lt; 12">

  Good morning.

  <elseif cond="hours &gt; 12   &amp;&amp; hours &lt; 18"/>

    Good Afternoon.

   <else/>

      Good evening.

</if>

'

&apos;

Not required.

ü

Used when attribute values are enclosed in single quotes rather than double quotes.

<value expr='Dante\&apos;s Peak'/>

"

&quot;

Not required.

ü

<value expr="I said &quot;Jump&quot;"/>

Quoted string

\

ü

ü

<script>
   var movie = 'Dante\'s Peak'
</script>

Note that it is also possible to escape an entire script by simply enclosing a CDATA section inside the opening and closing <script> elements, for example:

<script>
   <![CDATA[
      var prompt;
      if(hours > 2 && hours < 12)
        prompt = "Good morning.";
      else if(hours >= 12 && hours < 18)
        prompt = "Good afternoon.";
      else
       prompt = "Good evening.";
   ]]>
</script>