Javascript QuickStart

From FreeSWITCH Wiki
Jump to: navigation, search

This quick starts aims to help you with creating your first javascript application.

If you place the script in the "[FS root dir]/scripts" you may access them by their filename without any path information, if you place them elsewhere you must include the full path to the script eg:

[FS root dir]/scripts

<action application="javascript" data="HelloWorld.js" />

Full path example:

<action application="javascript" data="/var/scripts/HelloWorld.js" />


First application

Let's create a new application called HelloWorld.js and place it in the correct directory.

  var languageCode = "en";
  var soundDir = "sound/";

  function playFile(fileName, callBack, callBackArgs)
    session.streamFile(soundDir + languageCode + "/" + fileName, callBack, callBackArgs);


That wasn't so hard, was it? The first line specifies which language we are using. We can switch language anytime during the session thanks to this variable. The second variable specifies the root directory for the sound files.

We have created a own method call playFile which is used to play the correct language prompt. It also allows us to not care about where the sound files are located, which gives us DRY (Don't repeat yourself).

Session.answer() is the most important function in this script, since it answers.

Finally we have exit (not really necessary in this example, but I feel obliged to discuss it). exit is a magic method which will hangup on the user AND exit the script. There is another function called session.hangup() which will allow you to hangup on the user but not quit the javascript. This method is excellent if you need to like, write stuff to a database, or something like that.

Sound file

We have a complete javascript, but we will also need a sound file. Record or copy another .wav and place it (HelloWorld.wav) in the "sounds/en/us/callie/sounds/en/" folder.


Last thing to do is to add the javascript to our dialplan. Open "conf/default.xml" and add the following:

  <extension name="9910">
	<condition field="destination_number" expression="^9910$">
		<action application="javascript" data="HelloWorld.js" /> 

Now dial 9910 and enjoy your first javascript application.