spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / professional / chap4 / 3 To page 1To page 2To page 3current page
[previous]

Professional JavaScript

Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

Mixing JavaScript and VBScript

Microsoft's scripting architecture for Internet Explorer makes it possible to use a different language in each script block, simply by specifying the language attribute. It is then straightforward to call code in one language from another. At first glance these seems to be a great thing-and it used to be widely used-but today there are some alternatives you might want to consider before introducing the complexities of multiple languages. For example, you might want to mix languages to:

? Reuse code - If you have a library of code in one language, you can avoid having to rewrite it into another simply by calling across script blocks. Perhaps a better way to promote reuse, however, is to use DHTML or XML Scriptlets.

? Reuse skills - If different people on your team are trained in different languages, they can work together on the same page by mixing language calls. Of course, if you have enough code that this becomes an issue then the maintenance headaches from multiple languages might overshadow any savings.

? Leverage features not found in your "regular" language - Each interpreter has its own unique features and it can sometimes be worth the complexity of mixing languages to get at those features. Until fairly recently it was very worthwhile because, for example, VBScript didn't offer regular expressions and JScript didn't offer exception handling. In their latest releases both these shortcomings have been addressed and it's Microsoft's stated goal is to make the languages functionally equivalent. But they still aren't quite equivalent so if you need these out-of-your-language features, you have a good reason to mix languages. We'll see two examples of this next.

It's important to keep in mind that mixing languages can extend to any interpreter on your machine that supports the IActiveScript interface. Depending on your situation, Perl or other languages that are available as ActiveX components can provide powerful facilities not directly available in JavaScript.

The example below calls VBScript from JScript to take advantage of its MsgBox function, which offers all the options available in a Win32 message box including changing the button names and displaying a message icon. These options go well beyond what a scriptwriter normally has available with the browser's built-in alert() and confirm() methods.

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
<!--   //Define button values (same as VB/Win32 API MsgBox constants)

  var vbOK = 0;                        //Default is just an OK button
  var vbOKCancel = 1;                  //Display OK and Cancel buttons
  var vbAbortRetryIgnore = 2;          //Same for Abort, Retry, and Ignore
  var vbYesNoCancel = 3;               //...and so on
  var vbYesNo = 4;
  var vbRetryCancel = 5;

  //Define icons that show on message box
  var vbCritical = 16;                 //Display Critical Message (red X) icon
  var vbQuestion = 32;                 //Same for Warning Query icon.
  var vbExclamation = 48;              //...and so on
  var vbInformation = 64;
  var vbDefaultButton1 = 0;            //Make first button the default.
  var vbDefaultButton2 = 256;          //...and so on
  var vbDefaultButton3 = 512;
  var vbDefaultButton4 = 768;

  //Define "mode" of message box
  var vbApplicationModal = 0;    //Application modal; user must respond 
                                 //before script continues. This is the default.
  var vbSystemModal = 4096;      //System modal--well not quite. Actually just 
                                 //keeps message box "on top" of all other apps.

  function jsHandler() {
    //Call VB script to take advantage of better message box
    var iAns = vbsMessage(txtMessage.value,
                          vbYesNoCancel+vbQuestion, "Message from VBScript");



   //Example of how we might use returned value
   switch( iAns ) {
     case 1:          //OK
       alert("The user answered OK."); 
       break;
     case 2:          //Cancel
       alert("The user wants to Cancel."); 
       break;
     case 3:          //Abort
       alert("The user wants to Abort."); 
       break;
     case 4:          //Retry
       alert("The user wants to Retry."); 
       break;
     case 5:          //Ignore
       alert("The user wants to Ignore."); 
       break;
     case 6:          //Yes
       alert("The user answered Yes."); 
       break;
     case 7:          //no
       alert("The user answered No."); 
       break;
     default:         //"Never" happens
       alert("We don't know what they want!"); 
       break;
    }
  }
//--></SCRIPT>

<SCRIPT LANGUAGE="VBScript"><!--

  Function vbsMessage( sMsg, iStyle, sTitle )
    vbsMessage = MsgBox( sMsg, iStyle, sTitle )
  End function
--></SCRIPT>

</HEAD>
<BODY>
<P>Enter your question here: <INPUT id=txtMessage></P>
<P><INPUT ID=cmdShowMe TYPE=button VALUE="Show Me" ONCLICK="jsHandler()"></P>

</BODY
</HTML>

This example begins by defining some "constants" useful for the message box call. The mixed language call itself is very straightforward because all the primitive types map directly across. In fact the only common complexity in calling between these languages is VBScript's array type. JScript 3.0 introduced a special object (VBArray) to provide read-only access to VBScript arrays. For more on this special case, see the JScript documentation or http://msdn.microsoft.com/scripting/ jscript/doc/jsobjVBArray.htm.

In addition to MsgBox, VBScript has a few other features that JScript writers will need to access in this way, at least until the next version of our beloved language. VBScript has better support for date and currency calculations, a handy RGB function, and really valuable formatting functions. Anyone who's ever fought with indexOf() and substring() to format a date or currency value will really appreciate these functions.

For an example of calling JScript from VBScript we need to stretch a little further, or simply go back a version of the language. If you are using a version of JScript prior to 3.0, then it's a good idea to wrap your JScript code in a VBScript procedure to take advantage of the latter's exception handling. For client-side code, if you have enough control over your users to know they are using IE, you might prefer to require IE4. This includes JScript 3.0 and hence lets you use its native try..catch mechanism. You might be stuck without version 3.0 however, if you are developing server side JScript for delivery on a server with IIS 3.0 or earlier.

Whatever the reason, if JScript 3.0 isn't available to you, something like the following could ensure you catch all errors:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript"><!--
  function jsHandler(){
    //The following statement won't work well!
    noSuchObj.missingProp = 2; 
  }
//--></SCRIPT>

<SCRIPT LANGUAGE="VBScript"><!--
  ivbExclamation = 48

  'Wrap the JS handler in this nice safe VBS
  Function vbsHandler() 
    On Error Resume Next

    jsHandler()
    If Err.number<> 0 Then
      msgbox "Sorry, we had an error", ivbExclamation
    End If
  End Function
'--></SCRIPT>

</HEAD>

<BODY>
<P>Click here to crash and burn: 
<INPUT ID=cmdJS TYPE=button VALUE="Working Without a Net" ONCLICK="jsHandler()"> </P>
<P>Click here if you prefer to live safely: 
<INPUT ID=cmdVBS TYPE=button VALUE="Nice and Safe" onclick="vbsHandler()">
</P>

</BODY
</HTML>

In this example, we've purposely referenced a nonexistent object in the line

noSuchObj.missingProp = 2; 

Depending on the user's setup of IE, they will get one of several error messages... possibly even offering to let them debug our code (never a good idea).

In contrast, the VBScript handler, which calls the same flawed JScript code, uses its 'On Error Resume Next' statement to catch the error and allow us to handle it slightly more elegantly.

For those familiar with Visual Basic for Applications or for Windows, please note VBScript doesn't support any of the other On Error variants so you can't say

On Error Goto X

You have to handle the error inline, as the example above shows. Unfortunately it's a little tough to write a general purpose VBScript error-handler because prior to version 5.0 as it didn't have the equivalent of an eval() function.

home / programming / javascript / professional / chap4 / 3 To page 1To page 2To page 3current page
[previous]

Copyright 1999 (1st Edition) and 2001 (2nd Edition) Wrox Press Ltd. and

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

webref The latest from WebReference.com Browse >
Working with the DOM Stylesheets Collection · Administering RBAC in PHP 5 CMS Framework · xref: Automatic Cross Referencing Script
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Combine BottomCount() with Other MDX Functions to Add Sophistication · Creating a Daemon with Python · The Coming Voice-over-WiMAX Revolution


Revised: March 21, 2001
Created: March 21, 2001


URL: http://webreference.com/programming/javascript/professional/chap4/3/