JerryScript Engine can be embedded into any application, providing the way to run JavaScript in a large range of environments - from desktops to low-memory microcontrollers.

This guide is intended to introduce you to JerryScript embedding API through creation of simple JavaScript shell.

Step 1. Execute JavaScript from your application

  1. #include <string.h>
  2. #include "jerry-api.h"
  3. int
  4. main (int argc, char *argv[])
  5. {
  6. const jerry_char_t script[] = "print ('Hello, World!');";
  7. size_t script_size = strlen ((const char *) script);
  8. bool ret_value = jerry_run_simple (script, script_size, JERRY_INIT_EMPTY);
  9. return (ret_value ? 0 : 1);
  10. }

The application will generate the following output:

  1. Hello, World!

Step 2. Split engine initialization and script execution

Here we perform the same actions, as jerry_run_simple, while splitting into several steps:

  • engine initialization
  • script code setup
  • script execution
  • engine cleanup
  1. #include <string.h>
  2. #include "jerry-api.h"
  3. int
  4. main (int argc, char *argv[])
  5. {
  6. const jerry_char_t script[] = "print ('Hello, World!');";
  7. size_t script_size = strlen ((const char *) script);
  8. /* Initialize engine */
  9. jerry_init (JERRY_INIT_EMPTY);
  10. /* Setup Global scope code */
  11. jerry_value_t parsed_code = jerry_parse (script, script_size, false);
  12. if (!jerry_value_has_error_flag (parsed_code))
  13. {
  14. /* Execute the parsed source code in the Global scope */
  15. jerry_value_t ret_value = jerry_run (parsed_code);
  16. /* Returned value must be freed */
  17. jerry_release_value (ret_value);
  18. }
  19. /* Parsed source code must be freed */
  20. jerry_release_value (parsed_code);
  21. /* Cleanup engine */
  22. jerry_cleanup ();
  23. return 0;
  24. }

Our code is more complex now, but it introduces possibilities to interact with JerryScript step-by-step: setup native objects, call JavaScript functions, etc.

Step 3. Execution in ‘eval’-mode

  1. #include <string.h>
  2. #include "jerry-api.h"
  3. int
  4. main (int argc, char *argv[])
  5. {
  6. const jerry_char_t script_1[] = "var s = 'Hello, World!';";
  7. const jerry_char_t script_2[] = "print (s);";
  8. /* Initialize engine */
  9. jerry_init (JERRY_INIT_EMPTY);
  10. jerry_value_t eval_ret;
  11. /* Evaluate script1 */
  12. eval_ret = jerry_eval (script_1,
  13. strlen ((const char *) script_1),
  14. false);
  15. /* Free JavaScript value, returned by eval */
  16. jerry_release_value (eval_ret);
  17. /* Evaluate script2 */
  18. eval_ret = jerry_eval (script_2,
  19. strlen ((const char *) script_2),
  20. false);
  21. /* Free JavaScript value, returned by eval */
  22. jerry_release_value (eval_ret);
  23. /* Cleanup engine */
  24. jerry_cleanup ();
  25. return 0;
  26. }

This way, we execute two independent script parts in one execution environment. The first part initializes string variable, and the second outputs the variable.

Step 4. Interaction with JavaScript environment

  1. #include <string.h>
  2. #include "jerry-api.h"
  3. int
  4. main (int argc, char *argv[]) {
  5. const jerry_char_t str[] = "Hello, World!";
  6. const jerry_char_t script[] = "print (s);";
  7. /* Initializing JavaScript environment */
  8. jerry_init (JERRY_INIT_EMPTY);
  9. /* Getting pointer to the Global object */
  10. jerry_value_t global_object = jerry_get_global_object ();
  11. /* Constructing strings */
  12. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "s");
  13. jerry_value_t prop_value = jerry_create_string (str);
  14. /* Setting the string value as a property of the Global object */
  15. jerry_set_property (global_object, prop_name, prop_value);
  16. /* Releasing string values, as it is no longer necessary outside of engine */
  17. jerry_release_value (prop_name);
  18. jerry_release_value (prop_value);
  19. /* Releasing the Global object */
  20. jerry_release_value (global_object);
  21. /* Now starting script that would output value of just initialized field */
  22. jerry_value_t eval_ret = jerry_eval (script,
  23. strlen ((const char *) script),
  24. false);
  25. /* Free JavaScript value, returned by eval */
  26. jerry_release_value (eval_ret);
  27. /* Freeing engine */
  28. jerry_cleanup ();
  29. return 0;
  30. }

The sample will also output ‘Hello, World!’. However, now it is not just a part of the source script, but the value, dynamically supplied to the engine.

Step 5. Description of JerryScript value descriptors

JerryScript value can be a boolean, number, null, object, string or undefined. The value has an error flag, that indicates whether is an error or not. Every type has an error flag not only objects. The error flag should be cleared before the value is passed as an argument, otherwise it can lead to a type error. The error objects created by API functions has the error flag set.

The following example function will output a JavaScript value:

  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "jerry-api.h"
  4. #include "jerry-port.h"
  5. static void
  6. print_value (const jerry_value_t value)
  7. {
  8. if (jerry_value_is_undefined (value))
  9. {
  10. jerry_port_console ("undefined");
  11. }
  12. else if (jerry_value_is_null (value))
  13. {
  14. jerry_port_console ("null");
  15. }
  16. else if (jerry_value_is_boolean (value))
  17. {
  18. if (jerry_get_boolean_value (value))
  19. {
  20. jerry_port_console ("true");
  21. }
  22. else
  23. {
  24. jerry_port_console ("false");
  25. }
  26. }
  27. /* Float value */
  28. else if (jerry_value_is_number (value))
  29. {
  30. jerry_port_console ("number");
  31. }
  32. /* String value */
  33. else if (jerry_value_is_string (value))
  34. {
  35. /* Determining required buffer size */
  36. jerry_size_t req_sz = jerry_get_string_size (value);
  37. jerry_char_t str_buf_p[req_sz];
  38. jerry_string_to_char_buffer (value, str_buf_p, req_sz);
  39. str_buf_p[req_sz] = '\0';
  40. jerry_port_console ("%s", (const char *) str_buf_p);
  41. }
  42. /* Object reference */
  43. else if (jerry_value_is_object (value))
  44. {
  45. jerry_port_console ("[JS object]");
  46. }
  47. jerry_port_console ("\n");
  48. }

Simple JavaScript shell

Now all building blocks, necessary to construct JavaScript shell, are ready.

Shell operation can be described with the following loop:

  • read command;
  • if command is ‘quit’
    • exit loop;
  • else
    • eval (command);
    • print result of eval;
    • loop.
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "jerry-api.h"
  4. #include "jerry-port.h"
  5. static void print_value (const jerry_value_t);
  6. int
  7. main (int argc, char *argv[])
  8. {
  9. bool is_done = false;
  10. /* Initialize engine */
  11. jerry_init (JERRY_INIT_EMPTY);
  12. while (!is_done)
  13. {
  14. char cmd[256] = {};
  15. char *cmd_tail = cmd;
  16. size_t len = 0;
  17. jerry_port_console ("> ");
  18. /* Read next command */
  19. while (true)
  20. {
  21. if (fread (cmd_tail, 1, 1, stdin) != 1 && len == 0)
  22. {
  23. is_done = true;
  24. break;
  25. }
  26. if (*cmd_tail == '\n')
  27. {
  28. break;
  29. }
  30. cmd_tail++;
  31. len++;
  32. }
  33. /* If the command is "quit", break the loop */
  34. if (!strncmp (cmd, "quit\n", strlen ("quit\n")))
  35. {
  36. break;
  37. }
  38. jerry_value_t ret_val;
  39. /* Evaluate entered command */
  40. ret_val = jerry_eval ((const jerry_char_t *) cmd,
  41. len,
  42. false);
  43. /* If command evaluated successfully, print value, returned by eval */
  44. if (jerry_value_has_error_flag (ret_val))
  45. {
  46. /* Evaluated JS code thrown an exception
  47. * and didn't handle it with try-catch-finally */
  48. jerry_port_console ("Unhandled JS exception occured: ");
  49. }
  50. print_value (ret_val);
  51. jerry_release_value (ret_val);
  52. }
  53. /* Cleanup engine */
  54. jerry_cleanup ();
  55. return 0;
  56. }

The application inputs commands and evaluates them, one after another.

Step 6. Creating JS object in global context

In this example we demonstrate how to use native function and structures in JavaScript.

  1. #include <string.h>
  2. #include "jerry-api.h"
  3. struct my_struct
  4. {
  5. const char *msg;
  6. } my_struct;
  7. /**
  8. * Get a string from a native object
  9. */
  10. static jerry_value_t
  11. get_msg_handler (const jerry_value_t func_value, /**< function object */
  12. const jerry_value_t this_value, /**< this arg */
  13. const jerry_value_t *args_p, /**< function arguments */
  14. const jerry_length_t args_cnt) /**< number of function arguments */
  15. {
  16. return jerry_create_string ((const jerry_char_t *) my_struct.msg);
  17. } /* get_msg_handler */
  18. int
  19. main (int argc, char *argv[])
  20. {
  21. /* Initialize engine */
  22. jerry_init (JERRY_INIT_EMPTY);
  23. /* Do something with the native object */
  24. my_struct.msg = "Hello World";
  25. /* Create an empty JS object */
  26. jerry_value_t object = jerry_create_object ();
  27. /* Create a JS function object and wrap into a jerry value */
  28. jerry_value_t func_obj = jerry_create_external_function (get_msg_handler);
  29. /* Set the native function as a property of the empty JS object */
  30. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "myFunc");
  31. jerry_set_property (object, prop_name, func_obj);
  32. jerry_release_value (prop_name);
  33. jerry_release_value (func_obj);
  34. /* Wrap the JS object (not empty anymore) into a jerry api value */
  35. jerry_value_t global_object = jerry_get_global_object ();
  36. /* Add the JS object to the global context */
  37. prop_name = jerry_create_string ((const jerry_char_t *) "MyObject");
  38. jerry_set_property (global_object, prop_name, object);
  39. jerry_release_value (prop_name);
  40. jerry_release_value (object);
  41. jerry_release_value (global_object);
  42. /* Now we have a "builtin" object called MyObject with a function called myFunc()
  43. *
  44. * Equivalent JS code:
  45. * var MyObject = { myFunc : function () { return "some string value"; } }
  46. */
  47. const jerry_char_t script[] = " \
  48. var str = MyObject.myFunc (); \
  49. print (str); \
  50. ";
  51. size_t script_size = strlen ((const char *) script);
  52. /* Evaluate script */
  53. jerry_value_t eval_ret = jerry_eval (script, script_size, false);
  54. /* Free JavaScript value, returned by eval */
  55. jerry_release_value (eval_ret);
  56. /* Cleanup engine */
  57. jerry_cleanup ();
  58. return 0;
  59. }

The application will generate the following output:

  1. Hello World

Step 7. Extending JS Objects with native functions

Here we create a JS Object with jerry_eval, then extend it with a native function. This function shows how to get a property value from the object and how to manipulate it.

  1. #include <string.h>
  2. #include "jerry-api.h"
  3. /**
  4. * Add param to 'this.x'
  5. */
  6. static jerry_value_t
  7. add_handler (const jerry_value_t func_value, /**< function object */
  8. const jerry_value_t this_val, /**< this arg */
  9. const jerry_value_t *args_p, /**< function arguments */
  10. const jerry_length_t args_cnt) /**< number of function arguments */
  11. {
  12. /* Get 'this.x' */
  13. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "x");
  14. jerry_value_t x_val = jerry_get_property (this_val, prop_name);
  15. if (!jerry_value_has_error_flag (x_val))
  16. {
  17. /* Convert Jerry API values to double */
  18. double x = jerry_get_number_value (x_val);
  19. double d = jerry_get_number_value (*args_p);
  20. /* Add the parameter to 'x' */
  21. jerry_value_t res_val = jerry_create_number (x + d);
  22. /* Set the new value of 'this.x' */
  23. jerry_set_property (this_val, prop_name, res_val);
  24. jerry_release_value (res_val);
  25. }
  26. jerry_release_value (x_val);
  27. jerry_release_value (prop_name);
  28. return jerry_create_undefined ();
  29. } /* add_handler */
  30. int
  31. main (int argc, char *argv[])
  32. {
  33. /* Initialize engine */
  34. jerry_init (JERRY_INIT_EMPTY);
  35. /* Create a JS object */
  36. const jerry_char_t my_js_object[] = " \
  37. MyObject = \
  38. { x : 12, \
  39. y : 'Value of x is ', \
  40. foo: function () \
  41. { \
  42. return this.y + this.x; \
  43. } \
  44. } \
  45. ";
  46. jerry_value_t my_js_obj_val;
  47. /* Evaluate script */
  48. my_js_obj_val = jerry_eval (my_js_object,
  49. strlen ((const char *) my_js_object),
  50. false);
  51. /* Create a JS function object and wrap into a jerry value */
  52. jerry_value_t add_func_obj = jerry_create_external_function (add_handler);
  53. /* Set the native function as a property of previously created MyObject */
  54. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "add2x");
  55. jerry_set_property (my_js_obj_val, prop_name, add_func_obj);
  56. jerry_release_value (add_func_obj);
  57. jerry_release_value (prop_name);
  58. /* Free JavaScript value, returned by eval (my_js_object) */
  59. jerry_release_value (my_js_obj_val);
  60. const jerry_char_t script[] = " \
  61. var str = MyObject.foo (); \
  62. print (str); \
  63. MyObject.add2x (5); \
  64. print (MyObject.foo ()); \
  65. ";
  66. size_t script_size = strlen ((const char *) script);
  67. /* Evaluate script */
  68. jerry_value_t eval_ret = jerry_eval (script, script_size, false);
  69. /* Free JavaScript value, returned by eval */
  70. jerry_release_value (eval_ret);
  71. /* Cleanup engine */
  72. jerry_cleanup ();
  73. return 0;
  74. }

The application will generate the following output:

  1. Value of x is 12
  2. Value of x is 17

Further steps

For further API description, please visit API Reference page on JerryScript home page.