KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Executing an JavaScript expression in the Web Area
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: October 16, 2017

Want to execute a JavaScript expression quickly in 4D? Here is a utilty method to easily input a Javascript expression and output the result using the Web Area:

// ---------------------------------------------------------------------------
// Name: EXEC_JS_EXPRESSION_IN_WEBAREA
// Description: Method will execute an expression in the Web Area and
// return the result.
//
// Input:
// $1 (TEXT) - Expression input (e.g. "2*2", "23-11", "Math.pow(2,3)"
//
// Output:
// $0 (TEXT) - Result of the expression input
// ---------------------------------------------------------------------------
C_TEXT($1;$input;$html;$loc)
C_POINTER($2;$webAreaObj)
C_TEXT($0;$output)

If (Count parameters=2)
  $input:=$1
  $webAreaObj:=$2

  $html:="<!DOCTYPE><html><head><script>function executeExpression(){"
  $html:=$html+"return "+$input+";}</script><body></body></html>"

  TEXT TO DOCUMENT("index.html";$html)
  $loc:=Get 4D folder(Database folder)+"index.html"
  WA OPEN URL($webAreaObj->;$loc)
  DELAY PROCESS(Current process;1)
 
  ON ERR CALL("handle_error")
  WA EXECUTE JAVASCRIPT FUNCTION($webAreaObj->;"executeExpression";$0)
End if


Here are the steps to setup on a Form:

1. Place a Web Area in the form:



Moving the Web Area offscreen is a trick to not access the object shown below.



The Web Area needs to be on a form that can be activated with WA OPEN URL. The Web Area object can be minimized since it will not be interacted with the user.

2. Place Variable text on the form for input and output:



3. Button to execute the method



Where the following code will be placed in the button's object method:

Output:=EXEC_JS_EXPRESION_IN_WEBAREA (Expression;->WebArea)


Example #1 using as a calculator:



Example #2 using with a JavaScript Math function: