Adding Debugger Statements
Once script debugging is enabled, you need some code to debug. The easiest way to pop into debug mode for JavaScript is to add a debugger; statement in your script.
For a fun example, I wrote some code that uses the Speech API as an ActiveX object. The Speech API converts text to audio with a simple method call and a little configuration. The code in Listing 1 demonstrates a basic use of the Speech API; it's pretty short, but it gives you a lot of opportunity for debugging.
Listing 1Loading and testing the Speech API.
<script type="text/javascript"> debugger; var voice = new ActiveXObject("SAPI.SpVoice"); var voices = voice.GetVoices(); var len = voices.count; if (len >= 2) voice.Voice = voices(1); voice.Rate = 1; voice.Volume = 75; voice.Speak("Win a Segway from Developer Express at TechEd 2009"); </script>
The first step in using an ActiveX object is to turn on support for ActiveX objects. To permit the Speech API object to load, return to the Internet Options dialog in Internet Explorer or Visual Studio. Then adjust the security settings by following these steps:
- In the Internet Options dialog box, click the Security tab.
- Click the Local intranet zone icon (see Figure 2).
- Click the Custom Level button.
- In the Security Settings - Local Intranet Zone dialog box, scroll down to the ActiveX controls and plug-ins. Enable the option "Initialize and script ActiveX controls not marked as safe for scripting."
- Click OK to close the Security Settings dialog.
- Click OK to close the Internet Options dialog.
Figure 2 Change zone options to permit specific kinds of behaviors, such as permitting ActiveX code to run.
Based on the previous configuration settings, when you load the Speech API, Internet Explorer displays a warning before loading the control (see Figure 3).
Figure 3 Based on the changed configuration settings, a prompt will be displayed before the Speech API (an ActiveX object) is loaded.
When the Listing 1 code runs, it will inevitably hit the debugger; statement, and the Visual Studio debugger takes over (see Figure 4). That gives us an opportunity to explore how to use the capabilities of the Visual Studio debugger.
Figure 4 If script debugging is enabled, Visual Studio stops on every debugger; statement, which gives you ample opportunity to debug your JavaScript.