![]() |
Module 9: Advanced applications: using the e2gRuleEngine JavaScript interface to
dynamically control inferencing
Module 9 Index
Java applets like e2gRuleEngine cannot interact directly with the Web page in which they execute. It is, however, possible for an applet to call functions in client-side JavaScript programs and for these scripts to call methods in the applet. Since JavaScript can load Web pages and can write Web page content, interaction between e2gRuleEngine knowledge bases and the HTML defining a Web page is possible, permitting dynamic generation of HTML output as an expert system consultation progresses. As is almost always the case with Web implementations beyond the most basic, there are some potential hazards to consider before employing this e2gRuleEngine capability.
Considerations when using the e2gRuleEngine/JavaScript interface
![]() |
Browser incompatibilities and JavaScript: To use the JavaScript interface you must be familiar with JavaScript programming and the interaction of JavaScript with the elements of a Web page -- usually described by the Document Object Model (DOM). Some of the development issues are discussed in this documentation, but if you don't have (or have access to or a willingness to acquire) JavaScript expertise, or have a low tolerance for pain, working with the JavaScript interface might not be for you. |
![]() |
Security considerations:
The general capability to interface Java with JavaScript code
has played a part in several security exploits described on the Web.
If you are concerned with security issues, the Java/Javascript interface
was named "LiveConnect" (one word) by Netscape (its developer) and Googling
"LiveConnect security" or "Java Javascript security"
should get you to some worthwhile discussion of the issues. Here is a recommended link that includes a security discussion:
|
![]() |
Constraints imposed on the Web page format by the JavaScript interface: To use the e2gRuleEngine JavaScript interface, the <applet> tags that cause the e2gRuleEngine applet to be incorporated in a Web page and the JavaScript program with which it interacts should be in the same HTML file, and the page defined by this file must be persistent: it has to stay in the browser, unchanged, throughout the consultation. If the objective for using the interface is the dynamic loading or generation of HTML output, this means at least two HTML files must be present at the same time. This is accomplished by using frames. One frame contains the <applet> tags that invoke and display the applet along with the JavaScript program. Another frame (or frames) display(s) the dynamic HTML output. A new (optional) <PARAMETER> is added to the <applet> tags that names the JavaScript function to be called each time the user of the expert system presses a button displayed by the e2gRuleEngine applet. A number representing the button that has been pressed is passed to this function. A series of public methods called "accessors" in the e2gRuleEngine applet may then be called from the JavaScript code. These functions provide access to information about the current state of the consultation including the identity of the current goal attribute and the names, values and confidence factors associated with each of the attributes in the knowledge base for which a value has been determined. e2gRuleEngine also incorporates several "mutator" methods that allow attribute values and control parameters to be loaded into the current operation of the inference engine. These include the capability to change the active knowledge base, change display colors and restart the inference engine without reloading it. |
![]() |
The e2gRuleEngine/JavaScript interface is an advanced application: Expert systems applications requiring the JavaScript interface are best attempted after gaining experience with standalone e2gRuleEngine knowledge bases. The interface can be touchy -- especially when using the e2gRuleEngine methods that send data to e2gRuleEngine (mutators) rather than retrieving data (accessors). Incorrect use of these methods can cause the e2gRuleEngine program to crash. This documentation assumes existing knowledge of JavaScript programming. Extensive resources are available on the Web for learning to program with JavaScript, but this document does not provide such instruction. |
Building applications that use the JavaScript interface: wine selector demo
A simplified wine selector will be used to demonstrate how the JavaScript interface is applied to synchronize access to reference material or to produce dynamic HTML output. Click on the following image to open the demonstration program in a new browser window. Run the application, then return to this page for a discussion of each of its components:

The components of this application include the following. They all reside in the same subdirectory in this example:
Next, we'll examine each of these components to introduce the JavaScript interface:
winepg.htm: This is a standard frame definition document. Note that the frame that is to contain the dynamic output must be named: _infowin is the name in this example.
<html> <head><title>e2gRuleEngine Wine Demo</title></head> <frameset cols="450,*" frameborder=0 framespacing=0 border=0> <frame name="_applet" src="wine3.htm" marginheight=0 marginwidth=0> <frame name="_infowin" src="wineref.htm" marginheight=5 marginwidth=5> </frameset> </html> |
wine3.htm: The following listing describes the e2gRuleEngine applet and causes it to be loaded. It also provides the JavaScript code that will interact with e2gRuleEngine. Bold-faced lines are discussed in more detail following the listing:
<html>
<head><title>Basic Wine Selection Expert System</title></head>
<body bgcolor="#900000">
<applet code="e2gRuleEngine.class" archive="e2gRuleEngine.jar" name="e2g" width=445
height=300>
<param name="KBURL" value="wine.kb">
<param name="APPTITLE" value="Budget Wine Selector">
<param name="APPSUBTITLE" value="an eXpertise2Go Demonstration">
<param name="BGCOLOR" value="#900000">
<param name="TITLECOLOR" value="#ffffff">
<param name="PROMPTCOLOR" value="#ffffff">
<param name="STARTBUTTON" value="Help me choose a wine">
<param name="DEBUG" value="FALSE">
<param name="JSFUNCTION" value="buttonPush">
Java-enabled browser required
</applet>
<script language="Javascript">
function buttonPush(buttonNumber) {
if (buttonNumber == 1 || buttonNumber == 6) { //Start or restart
window.open("wineref.htm#TOP","_infowin"); //Reposition reference
} else if (buttonNumber == 2) {
goalIx = document.e2g.getGoalAttr();
if (goalIx == 0) {
//Finished
parent._infowin.document.open("text/html");
//NOTE: Be careful not to break string literals (next statement) between lines
parent._infowin.document.write("<html><body bgcolor='#900000'>" +
"<font size='5' color='white'><center>Thanks for visiting " + new Date() +
"<p>Please shop at Charlie's Budget Wines</center></font></body></html>");
parent._infowin.document.close();
} else {
goalName = document.e2g.getAttrName(goalIx);
if (goalName == "the preferred body") {
window.open("wineref.htm#BODY","_infowin");
} else if (goalName == "the preferred taste") {
window.open("wineref.htm#DRYNESS","_infowin");
}
}
}
}
</script>
</body>
</html>
|
Here are some considerations in the above code that differentiate an application using the JavaScript interface from other e2gRuleEngine applications:
| Button Codes Provided by e2gRuleEngine | ||
|---|---|---|
| Button Clicked | Value | |
| Initialization (before startup screen - no button action) | 0 | |
| Start the consultation * | 1 | |
| Submit your response | 2 | |
| Why Ask? | 3 | |
| Return (from Why Ask?) | 4 | |
| Explain | 5 | |
| Restart | 6 | |
| JSHyperlink clicked (v7.0+) | 9 | |
| * May be renamed by the STARTBUTTON applet parameter. Other buttons may be renamed by knowledge base TRANSLATE commands. | ||
The statement:
If the consultation is finished, JavaScript's
capability for directly creating an HTML document in a window is employed
to output a final message. To do this you must open a window for output,
write text representing an HTML document to the window, then close it.
To use these JavaScript methods (
| e2gRuleEngine Methods Accessible from JavaScript | ||
|---|---|---|
| Method Name | Value Returned and Value Type | Arguments and Argument Types |
| getAttrCF(attrIx) | (Float) Confidence factor associated with specific instance of named attribute (0.0 if doesn't exist or net yet determined) | (Integer) attrIx: index of attribute (between 1 and number of attributes) |
| getAttrCF(attrName, valIx) | (Float) Confidence factor associated with specific instance of named attribute (0.0 if doesn't exist or net yet determined) | (String) attrName: name of attribute (Integer) valIx: instance (between 1 and max values) of named attribute to allow for multi-valued attributes |
| getAttrCount( ) | (Integer) Number of attributes defined in the knowledge base | |
| getAttrIx(attrName, valIx) | (Integer) Index of attribute associated with specific instance of named attribute (0 if doesn't exist) | (String) attrName: name of attribute (Integer) valIx: instance (between 1 and max values) of named attribute to allow for multi-valued attributes |
| getAttrName(attrIx) | (String) Name of attribute (zero length string if doesn't exist) | (Integer) attrIx: index of attribute |
| getAttrValue(attrIx) | (String) String representation of current value (0 length string if doesn't exist or not yet determined) | (Integer) attrIx: index of attribute |
| (String) String representation of current value (0 length string if doesn't exist or not yet determined) | (String) attrName: name of attribute (Integer) valIx: instance (between 1 and max values) of named attribute to allow for multi-valued attributes | |
| getMaxValues(attrName) | (Integer) Number of values (instances) allowed for named attribute (0 if doesn't exist) | (String) attrName: name of attribute |
| getGoalAttr( ) | (Integer) Index of current goal or subgoal attribute (0 if inferencing is finished) | |
| loadValue(attrName, attrValue, attrCF) | (Integer) 0 if attribute value loaded successfully, -1 if attribute not found in KB | (String) attrName: name of attribute to load as if from PROMPT (String) attrValue: value to load (always input as text string: e2gRuleEngine converts if necessary) (Float) attrCF: CF to set for loaded attribute |
| restartE2g(KBUrl, bypassResults) | (Integer) 0 for OK | (String) KBUrl: URL of knowledge base to load (Boolean) bypassResults: if true, bypass display of current consultation results |
| resetColors(strBColor, strPColor, strTColor) | (Integer) 0 for OK | (String) strBColor: new background color (#rrggbb) (String) strPColor: new prompt text color (#rrggbb) (String) strTColor: new application title text color (#rrggbb) |
| setAppTitle(appTitle) | (Integer) 0 for OK | (String) appTitle: new application title |
| Note 1: e2gRuleEngine attributes are identified with a name and index number
that begins at 1.
Every attribute value has a unique index, but all values of multivalued
attributes are stored with the same name.
Note 2: A value for an attribute will not be returned until the value is known with a confidence factor at least equal to the minimum CF. Note 3: loadValue(), restartE2g(), resetColors() and setAppTitle() are mutators provided to support applications that switch knowledge bases during a consultation. Note 4: loadValue() may be called more than once with the same attrName if attribute is multivalued. | ||
wineref.htm: This standard HTML document won't be shown here because of its length, but you may examine the HTML code with your browser's "view source" capability when you run the wine selection demonstration. Note the inclusion of anchor tags of the form:
that are used by the JavaScript
wine.kb: A standard e2gRuleEngine knowledge base. To examine or download the knowledge base click here:
e2gRuleEngine public methods demonstration program
An example that provides a more comprehensive demonstration of the public methods available in e2gRuleEngine is accessible from the following link. The example will run in a new window. It is an implementation of the Graduate School Admissions knowledge base (acessible from module 1) that displays the state of each of the attributes after each user action.
Using your browser's "View Source" capability in the browser's left pane after loading the example will let you examine the JavaScript code that supports the demonstration.
Using the JavaScript interface to implement linked knowledge bases: a diagnostic example
It is often possible to use the natural structure of a problem to group related rules into knowlege bases that are linked as necessary during the course of a consultation. This will especially be the case for diagnostic systems. For example, the automobile diagnostic knowledge base that has been used as an example in many of the modules could be restructured into three knowledge bases as follows:

The expert system would initially load the "Subsystem Identification" knowledge base that would use prompts and rules to determine whether the "Fuel" or "Electrical" subsystems were the most likely source of the problem. Then, the appropriate subsystem knowledge base would be loaded, and the consultation continued. If the fuel subsystem is initially investigated, and the problem is not identified in this subsystem, the user might be switched to the electrical subsystem and the consultation extended. Information extracted while interacting with any individual knowledge base should be maintained as input to the next linked component.
It is easy to visualize other forms of diagnostic applications, including medical diagnosis, that might begin at a general level then focus in on more specific symptoms, linking subsystem knowledge bases as required.
Advantages of decomposing the rule base when implementing expert systems include:
Linked knowledge bases may be implemented with the e2gRuleWriter inference engine through a set of methods provided for the JavaScript interface that support input to the rule engine while it is running. The values input to the inference engine may be determined by rules in the knowledge bases: rules that control the operation of an expert system are called metarules. e2gRuleEngine metarules differ from other rules in a knowledge base only in their purpose: they conclude Tovalues of attributes that are used by the JavaScript interface to control movement among the linked knowledge bases.
To illustrate the operation of a decomposed rule base, click on this image to run an application that implements the automobile subystem structure shown in the previous diagram:
This demonstration includes three knowledge bases: automain.kb that contains metarules and prompts used to determine the next knowledge base to load, autofuel.kb that contains rules and prompts to diagnose fuel subsystem problems and autoelec.kb that contains rules and prompts to diagnose electrical subsystem problems. The autofuel.kb knowledge base also incorporates a metarule that fires if a fuel problem is not found and causes control to transfer to the autoelec.kb knowledge base. Background colors and application titles are changed as the consultation progresses to indicate which knowledge base is currently operating: yellow background when automain.kb is employed, blue for autofuel.kb and green for autoelec.kb. When the "restart" button is pressed anywhere during a consultation, control transfers to the automain.kb startup knowledge base.
You may want to try a few of the following input combinations to see how the linked knowledge base example works, then look at an explanation of the knowledge bases and the JavaScript code that implements the linking process:
| Linked knowledge base example: test case 1 | ||
|---|---|---|
| Prompt | Your Response | Result |
| What happens when you turn the key... | the car cranks normally | Link to autofuel.kb (blue) |
| According to the gas guage, the tank... | not empty | Link to autoelec.kb (green) |
| The result of switching on the headlights... | nothing happens | final result: recharge battery |
| Press the restart key |   | Link to automain.kb to restart (yellow) |
| Linked knowledge base example: test case 2 | ||
| Prompt | Your Response | Result |
| What happens when you turn the key... | nothing happens | Link to autoelec.kb (green), immediately get final result: recharge battery |
| Press the restart key |   | Link to automain.kb to restart (yellow) |
| Linked knowledge base example: test case 3 | ||
| Prompt | Your Response | Result |
| What happens when you turn the key... | the car cranks slowly | Link to autoelec.kb (green) |
| The result of switching on the headlights is... | they light up | Headlights dim... (prompt) |
| Do the headlights dim when you try the starter... | yes | How much willing to spend... (prompt) |
| How much are you willing to spend... | 50 | final result: recharge battery |
| Press the restart key |   | Link to automain.kb to restart (yellow) |
Now we'll examine the knowledge bases, HTML and JavaScript necessary to implement this example.
| automain.kb |
|---|
REM demo linked knowledge bases: this is the root knowledge base Rule [electrical subsystem metarule] If [the result of trying the starter] : "nothing happens" "the car cranks slowly" Then [nextKB] = "autoelec.kb" and [nextAppTitle] = "Diagnose electrical system problem" and [nextBGColor] = "#00ff00" and [nextPColor] = "#000000" and [nextTColor] = "#ffff00" Rule [fuel subsystem metarule] If [the result of trying the starter] = "the car cranks normally" Then [nextKB] = "autofuel.kb" and [nextAppTitle] = "Diagnose fuel system problem" and [nextBGColor] = "#0000ff" and [nextPColor] = "#ffff00" and [nextTColor] = "#ffffff" PROMPT [the result of trying the starter] Choice CF "What happens when you turn the key to try to start the car?" "the car cranks normally" "the car cranks slowly" "nothing happens" GOAL [nextKB] MINCF 80 |
The automain.kb knowledge base contains two e2gRuleEngine rules representing metarules that determine values for the control attributes. Four expert system attributes are used in our JavaScript/e2gRuleEngine interface example to control the inferencing logic:
Notice that the goal attribute for the automain.kb knowledge base is nextKB, the name of the next knowledge base to load. If the response to the prompt is "the car cranks normally" the value of nextKB will be set to autofuel.kb:
| autofuel.kb |
|---|
REM demo linked knowledge bases: this is the fuel subsystem knowledge base RULE [Is the car out of gas?] If [the gas tank] = "empty" Then [the recommended action] = "refuel the car" RULE [Is the gas tank empty?] If [the result of trying the starter] = "the car cranks normally" and [a gas smell] = "not present when trying the starter" Then [the gas tank] = "empty" @ 90 RULE [Metarule try the electrical KB by default] if [the recommended action] = "try the electrical knowledge base" Then [nextKB] = "autoelec.kb" and [nextAppTitle] = "Diagnosis electrical system problem" and [nextBGColor] = "#00ff00" and [nextPColor] = "#000000" and [nextTColor] = "#ffff00" PROMPT [a gas smell] MultChoice CF "The smell of gasoline is:" "present when trying the starter" "not present when trying the starter" PROMPT [the gas tank] MultChoice CF "According to the fuel gauge, the gas tank is:" "empty" "not empty" DEFAULT [the gas tank] = "empty" @ 90 DEFAULT [the recommended action] = "try the electrical knowledge base" GOAL [the recommended action] MINCF 80 |
The autofuel.kb knowledge base contains rules and prompts that may identify an out of fuel condition. It also contains a metarule that links to the autoelec.kb knowledge base if the recommended action goal variable is not determined by the user's responses to the prompts. This is accomplished by using a default setting of the goal variable (the recommended action) to fire the metarule.
| autoelec.kb |
|---|
REM demo linked knowledge bases: this is the electrical subsystem knowledge base RULE [Is the battery dead?] If [the result of switching on the headlights] = "nothing happens" or [the result of trying the starter] = "nothing happens" Then [the recommended action] = "recharge or replace the battery" RULE [Is the battery weak?] If [the result of trying the starter] = "the car cranks slowly" and [the headlights dim when trying the starter] = true and [the amount you are willing to spend on repairs] > 24.99 Then [the recommended action] = "recharge or replace the battery" PROMPT [the result of trying the starter] Choice CF "What happens when you turn the key to try to start the car?" "the car cranks normally" "the car cranks slowly" "nothing happens" PROMPT [the result of switching on the headlights] MultChoice CF "The result of switching on the headlights is:" "they light up" "nothing happens" PROMPT [the headlights dim when trying the starter] YesNo CF "Do the headlights dim when you try the starter with the lights on?" PROMPT [the amount you are willing to spend on repairs] Numeric CF "How much are you willing to spend on repairs? (enter value 0->500)" "0.0" "500.0" DEFAULT [the amount you are willing to spend on repairs] = 30 GOAL [the recommended action] MINCF 80 |
The autoelec.kb knowledge base is a collection of rules and prompts intended to determine if the battery needs to be replaced or recharged. There is no metarule in this knowledge base to link the application any further: if no value of the goal variable the recommended action is determined, the consultation will end at this point with a message that the goal could not be determined.
The following annotated listing is the source code for a Web page that implements linked knowledge bases using the automobile diagnostic case as an example. Areas of the code that need to be modified to accommodate different applications are displayed in blue. To download the program listing right click here and follow your browser's instructions for saving the link.
| linkdemo.htm (explanatory text with gray background is not part of the program listing) | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
<HTML> <HEAD><TITLE>Auto Diagnosis Expert System</TITLE></HEAD> <BODY BGCOLOR="yellow"> <center> <applet code="e2gRuleEngine" archive="e2gRuleEngine.jar" name="e2g" width=450 height=350> <param name="KBURL" VALUE="automain.kb"> <param name="APPTITLE" VALUE="Auto Diagnosis Advisor"> <param name="APPSUBTITLE" VALUE="Linked knowledge base demonstration"> <param name="titlecolor" value="#0000ff"> <param name="DEBUG" VALUE="false"> <param name="JSFUNCTION" value="buttonPush"> Java-capable browser required! </applet> </center> | |||||||||||||
| This is the HTML code that sets up the starting level of the application. Note the use of the name="e2g" attribute on the <applet> tag line and the inclusion of the <param name="JSFUNCTION" value="buttonPush"> parameter. Names identifying the applet and the function that e2gRuleEngine will call as buttons are pressed must be provided, and this is how it is done. | |||||||||||||
<!--JavaScript to link knowledge bases--> <script language="JavaScript"> |
Debugging e2gRuleEngine/JavaScript interface applications:
Built-in and supplemental facilities that support debugging JavaScript code vary
from browser to browser, and it is beyond
the scope of this document to discuss these in detail. Browser documentation and Internet references
provide specific information about acquiring, enabling and using these debuggers.
As an example, the Mozilla Firefox
browser incorporates a built-in error console that is easy to use and may provide sufficient
debugging information without resorting to more sophisticated test support.
The Error Console accessed from the Firefox Tools menu shows information about JavaScript
errors. Coding errors are displayed with an error message, the erroneous statement and the position
of the error clearly indicated as shown in the first error message in the following example
from a JavaScript program that omitted a required right parenthesis on line 35:

The second error shown in the above error console output results from invoking an e2gRuleEngine/JavaScript interface method with a parameter of the incorrect type -- in this case we forced the error by invoking one of the e2gRuleEngine methods with a null value for a parameter that should be a number.
Because errors accumulate in this window from the time the browser is loaded, you may want to click the "clear" key before starting a test run. Many popular Web pages produce minor JavaScript errors, so the console is often loaded with output.
If e2gRuleEngine is run in the "debug" mode, an error message like the one below is produced in the Knowledge Base Developer's Output window along with the error console output:

Identifying the specific button push that led to the error could be helpful in locating the the JavaScript code that caused the error.
It is sometimes useful to build a custom test environment while an application is under development. To run the test environment used while creating the automobile diagnosis linked knowledge base example click here to run linkframe.htm. This example opens a new window with a split frame that runs e2gRuleEngine in the left pane and displays diagnostic output from the JavaScript code in the right pane. You may examine the code for this test environment by right clicking the following link and downloading the listing: autolink.htm along with the linkframe.htm Web page. Examining the structure of this code could be helpful in developing a test environment suitable for your own program.
The following frustrating problem often occurs while developing JavaScript applications: You run a test, and your program fails. You identify the problem, modify the code and run the program again -- and it fails again as if you haven't altered the code. The problem may be that the browser is still running the old version of the code. To find out, use the browser's function that lets you examine the page source code. If your application runs your applet in a frame, you must right click in the frame to look at the frame's source code. Browsers, in the interest of efficiency, cache Web pages to avoid downloading them repeatedly, so you may have to force a reload of the page to test your modifications. With Mozilla Firefox and Microsoft Explorer you can right click in the frame that contains the page with your JavaScript and use the "reload page" option that appears on the popup menu. To reload a page in a frame in Google's Chrome browser, click on the tool menu (the little wrench icon), then select the "Clear browsing data" entry and clear the cache before reloading.
Finally, when you have developed an application using the JavaScript/e2gRuleEngine interface and have it working, be sure to test it with other browsers -- you may be unpleasantly surprised to find that JavaScript that works properly in one browser requires some tweaking to run in another.