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 and to create a minimal JavaScript shell. The examples are not using all API methods please also check out the API reference document which contains additional examples.

Before trying out the examples: Get and build JerryScript library

Before getting started using the JerryScript library it should be cloned and built for a target os/device.

There are quite a few configuration options but for these examples the JerryScript is built with default configuration and installed to a user directory on a Linux system. This is done by the following commands:

  1. $ mkdir jerry
  2. $ cd jerry
  3. $ git clone https://github.com/jerryscript-project/jerryscript.git
  4. $ jerryscript/tools/build.py --builddir=$(pwd)/example_build --cmake-param="-DCMAKE_INSTALL_PREFIX=$(pwd)/example_install/"
  5. $ make -C $(pwd)/example_build install

With this the JerryScript library is installed into the $(pwd)/example_install/{include,lib} directories.

In this guide we will use pkg-config to ease the usage of headers and libraries. In order to do so, the following export is required (executed from the jerry directory):

  1. $ export PKG_CONFIG_PATH=$(pwd)/example_install/lib/pkgconfig/

Test if the pkg-config works for JerryScript:

  1. $ pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-ext libjerry-libm

Example 1. Execute JavaScript from your application

The most basic example to test the engine is to create an api-example-1.c file containing the following code:

  1. #include "jerryscript.h"
  2. int
  3. main (void)
  4. {
  5. const jerry_char_t script[] = "var str = 'Hello, World!';";
  6. bool ret_value = jerry_run_simple (script, sizeof (script) - 1, JERRY_INIT_EMPTY);
  7. return (ret_value ? 0 : 1);
  8. }

To compile it one can use the following command:

  1. $ gcc api-example-1.c -o api-example-1 $(pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-libm)

If everything is correct the application returns with a zero exit code:

  1. $ ./api-example-1
  2. $ echo $?

Example 2. Split engine initialization and script execution.

In this example the engine is initialized directly with the jerry_init method and cleaned up with the jerry_cleanup method. The example JavaScript code is directly parsed and executed via the jerry_eval method. Each jerry_value_t returned by the API methods is freed with the jerry_release_value method.

To make sure that the code parsing and execution was ok, the jerry_value_is_error method is used to check for any errors.

Use the following code for the api-example-2.c file:

  1. #include "jerryscript.h"
  2. int
  3. main (void)
  4. {
  5. const jerry_char_t script[] = "var str = 'Hello, World!';";
  6. const jerry_length_t script_size = sizeof (script) - 1;
  7. /* Note: sizeof can be used here only because the compiler knows the static character arrays's size.
  8. * If this is not the case, strlen should be used instead.
  9. */
  10. /* Initialize engine */
  11. jerry_init (JERRY_INIT_EMPTY);
  12. /* Run the demo script with 'eval' */
  13. jerry_value_t eval_ret = jerry_eval (script,
  14. script_size,
  15. JERRY_PARSE_NO_OPTS);
  16. /* Check if there was any error (syntax or runtime) */
  17. bool run_ok = !jerry_value_is_error (eval_ret);
  18. /* Parsed source code must be freed */
  19. jerry_release_value (eval_ret);
  20. /* Cleanup engine */
  21. jerry_cleanup ();
  22. return (run_ok ? 0 : 1);
  23. }

To compile it one can use the following command:

  1. $ gcc api-example-2.c -o api-example-2 $(pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-libm)

If everything is correct the application returns with a zero exit code:

  1. $ ./api-example-2
  2. $ echo $?

Example 3. Split JavaScript parsing and script execution

In this example the jerry_eval is replaced with a more common API calls:

  • script code setup - jerry_parse.
  • script execution - jerry_run.

The api-example-3.c file should contain the following code:

  1. #include "jerryscript.h"
  2. int
  3. main (void)
  4. {
  5. bool run_ok = false;
  6. const jerry_char_t script[] = "var str = 'Hello, World!';";
  7. /* Initialize engine */
  8. jerry_init (JERRY_INIT_EMPTY);
  9. /* Setup Global scope code */
  10. jerry_value_t parsed_code = jerry_parse (NULL, 0, script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
  11. /* Check if there is any JS code parse error */
  12. if (!jerry_value_is_error (parsed_code))
  13. {
  14. /* Execute the parsed source code in the Global scope */
  15. jerry_value_t ret_value = jerry_run (parsed_code);
  16. /* Check the execution return value if there is any error */
  17. run_ok = !jerry_value_is_error (ret_value);
  18. /* Returned value must be freed */
  19. jerry_release_value (ret_value);
  20. }
  21. /* Parsed source code must be freed */
  22. jerry_release_value (parsed_code);
  23. /* Cleanup engine */
  24. jerry_cleanup ();
  25. return (run_ok ? 0 : 1);
  26. }

To compile it one can use the following command:

  1. $ gcc api-example-3.c -o api-example-3 $(pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-libm)

If everything is correct the application returns with a zero exit code:

  1. $ ./api-example-3
  2. $ echo $?

Example 4. Adding a C method for JavaScript

The previous examples were not that eye catching as there were no visual output by the JavaScript code and C program.

In this example a very simple “print” method is added which prints out a static string. This method will be implemented in C and will be called from the JavaScript code. For this a few extra API methods are required:

  • jerry_get_global_object
  • jerry_create_string
  • jerry_set_property
  • jerry_create_external_function

The api-example-4.c file should contain the following code:

  1. #include <stdio.h>
  2. #include "jerryscript.h"
  3. static jerry_value_t
  4. print_handler (const jerry_value_t function_object,
  5. const jerry_value_t function_this,
  6. const jerry_value_t arguments[],
  7. const jerry_length_t argument_count)
  8. {
  9. /* No arguments are used in this example */
  10. /* Print out a static string */
  11. printf ("Print handler was called\n");
  12. /* Return an "undefined" value to the JavaScript engine */
  13. return jerry_create_undefined ();
  14. }
  15. int
  16. main (void)
  17. {
  18. const jerry_char_t script[] = "print ();";
  19. const jerry_length_t script_size = sizeof (script) - 1;
  20. /* Initialize engine */
  21. jerry_init (JERRY_INIT_EMPTY);
  22. /* Add the "print" method for the JavaScript global object */
  23. {
  24. /* Get the "global" object */
  25. jerry_value_t global_object = jerry_get_global_object ();
  26. /* Create a "print" JS string */
  27. jerry_value_t property_name_print = jerry_create_string ((const jerry_char_t *) "print");
  28. /* Create a function from a native C method (this function will be called from JS) */
  29. jerry_value_t property_value_func = jerry_create_external_function (print_handler);
  30. /* Add the "print" property with the function value to the "global" object */
  31. jerry_value_t set_result = jerry_set_property (global_object, property_name_print, property_value_func);
  32. /* Check if there was no error when adding the property (in this case it should never happen) */
  33. if (jerry_value_is_error (set_result)) {
  34. printf ("Failed to add the 'print' property\n");
  35. }
  36. /* Release all jerry_value_t-s */
  37. jerry_release_value (set_result);
  38. jerry_release_value (property_value_func);
  39. jerry_release_value (property_name_print);
  40. jerry_release_value (global_object);
  41. }
  42. /* Setup Global scope code */
  43. jerry_value_t parsed_code = jerry_parse (NULL, 0, script, script_size, JERRY_PARSE_NO_OPTS);
  44. if (!jerry_value_is_error (parsed_code))
  45. {
  46. /* Execute the parsed source code in the Global scope */
  47. jerry_value_t ret_value = jerry_run (parsed_code);
  48. /* Returned value must be freed */
  49. jerry_release_value (ret_value);
  50. }
  51. /* Parsed source code must be freed */
  52. jerry_release_value (parsed_code);
  53. /* Cleanup engine */
  54. jerry_cleanup ();
  55. return 0;
  56. }

To compile it one can use the following command:

  1. $ gcc api-example-4.c -o api-example-4 $(pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-libm)

If everything is correct the application should print out the message present in the print_handler method:

  1. $ ./api-example-4

Example 5. Passing and processing arguments for native C code

In the previous example the print_handler simply wrote a static string to the standard output. However in most cases this is not useful, ideally the method’s argument(s) should be printed.

In this example the print_handler is extended to convert the first argument (which probably comes from a JavaScript source) to a JS string and prints it out to the standard output.

New API methods used:

  • jerry_value_to_string
  • jerry_string_to_utf8_char_buffer

The api-example-5.c file should contain the following code:

  1. #include <stdio.h>
  2. #include "jerryscript.h"
  3. static jerry_value_t
  4. print_handler (const jerry_value_t function_object,
  5. const jerry_value_t function_this,
  6. const jerry_value_t arguments[],
  7. const jerry_length_t arguments_count)
  8. {
  9. /* There should be at least one argument */
  10. if (arguments_count > 0)
  11. {
  12. /* Convert the first argument to a string (JS "toString" operation) */
  13. jerry_value_t string_value = jerry_value_to_string (arguments[0]);
  14. /* A naive allocation of buffer for the string */
  15. jerry_char_t buffer[256];
  16. /* Copy the whole string to the buffer, without a null termination character,
  17. * Please note that if the string does not fit into the buffer nothing will be copied.
  18. * More details on the API reference page
  19. */
  20. jerry_size_t copied_bytes = jerry_string_to_utf8_char_buffer (string_value, buffer, sizeof (buffer) - 1);
  21. buffer[copied_bytes] = '\0';
  22. /* Release the "toString" result */
  23. jerry_release_value (string_value);
  24. printf ("%s\n", (const char *)buffer);
  25. }
  26. /* Return an "undefined" value to the JavaScript engine */
  27. return jerry_create_undefined ();
  28. }
  29. int
  30. main (void)
  31. {
  32. const jerry_char_t script[] = "print ('Hello from JS!');";
  33. const jerry_length_t script_size = sizeof (script) - 1;
  34. /* Initialize engine */
  35. jerry_init (JERRY_INIT_EMPTY);
  36. /* Add the "print" method for the JavaScript global object */
  37. {
  38. /* Get the "global" object */
  39. jerry_value_t global_object = jerry_get_global_object ();
  40. /* Create a "print" JS string */
  41. jerry_value_t property_name_print = jerry_create_string ((const jerry_char_t *) "print");
  42. /* Create a function from a native C method (this function will be called from JS) */
  43. jerry_value_t property_value_func = jerry_create_external_function (print_handler);
  44. /* Add the "print" property with the function value to the "global" object */
  45. jerry_value_t set_result = jerry_set_property (global_object, property_name_print, property_value_func);
  46. /* Check if there was no error when adding the property (in this case it should never happen) */
  47. if (jerry_value_is_error (set_result)) {
  48. printf ("Failed to add the 'print' property\n");
  49. }
  50. /* Release all jerry_value_t-s */
  51. jerry_release_value (set_result);
  52. jerry_release_value (property_value_func);
  53. jerry_release_value (property_name_print);
  54. jerry_release_value (global_object);
  55. }
  56. /* Setup Global scope code */
  57. jerry_value_t parsed_code = jerry_parse (NULL, 0, script, script_size, JERRY_PARSE_NO_OPTS);
  58. if (!jerry_value_is_error (parsed_code))
  59. {
  60. /* Execute the parsed source code in the Global scope */
  61. jerry_value_t ret_value = jerry_run (parsed_code);
  62. /* Returned value must be freed */
  63. jerry_release_value (ret_value);
  64. }
  65. /* Parsed source code must be freed */
  66. jerry_release_value (parsed_code);
  67. /* Cleanup engine */
  68. jerry_cleanup ();
  69. return 0;
  70. }

To compile it one can use the following command:

  1. $ gcc api-example-5.c -o api-example-5 $(pkg-config --cflags --libs libjerry-core libjerry-port-default libjerry-libm)

If everything is correct the application should print out the string passed for the print method in the JS code:

  1. $ ./api-example-5

Example 6. Using JerryScript Extensions

Some of the previous examples used a “print” method to write data out to the standard output. For convenience JerryScript provides an extension to add a simple “print” handler which can be used by other applications.

In this example the following extension methods are used:

  • jerryx_handler_register_global
  • jerryx_handler_print

In further examples this “print” handler will be used.

  1. #include "jerryscript.h"
  2. #include "jerryscript-ext/handler.h"
  3. int
  4. main (void)
  5. {
  6. const jerry_char_t script[] = "print ('Hello from JS with ext!');";
  7. const jerry_length_t script_size = sizeof (script) - 1;
  8. /* Initialize engine */
  9. jerry_init (JERRY_INIT_EMPTY);
  10. /* Register 'print' function from the extensions to the global object */
  11. jerryx_handler_register_global ((const jerry_char_t *) "print",
  12. jerryx_handler_print);
  13. /* Setup Global scope code */
  14. jerry_value_t parsed_code = jerry_parse (NULL, 0, script, script_size, JERRY_PARSE_NO_OPTS);
  15. if (!jerry_value_is_error (parsed_code))
  16. {
  17. /* Execute the parsed source code in the Global scope */
  18. jerry_value_t ret_value = jerry_run (parsed_code);
  19. /* Returned value must be freed */
  20. jerry_release_value (ret_value);
  21. }
  22. /* Parsed source code must be freed */
  23. jerry_release_value (parsed_code);
  24. /* Cleanup engine */
  25. jerry_cleanup ();
  26. return 0;
  27. }

To compile it one can use the following command:

(Note that the libjerry-ext was added before the libjerry-port-default entry for the pkg-config call.

  1. $ gcc api-example-6.c -o api-example-6 $(pkg-config --cflags --libs libjerry-core libjerry-ext libjerry-port-default libjerry-libm)

If everything is correct the application should print out the string passed for the print method in the JS code:

  1. $ ./api-example-6

Example 7. Interaction with JavaScript environment - adding a string property

Previously a C method was registered for the global object, now this examples show how one can add a string property.

Use the following code as the api-example-7.c file:

  1. #include "jerryscript.h"
  2. #include "jerryscript-ext/handler.h"
  3. int
  4. main (void)
  5. {
  6. const jerry_char_t script[] = "print (my_var);";
  7. /* Initializing JavaScript environment */
  8. jerry_init (JERRY_INIT_EMPTY);
  9. /* Register 'print' function from the extensions */
  10. jerryx_handler_register_global ((const jerry_char_t *) "print",
  11. jerryx_handler_print);
  12. /* Getting pointer to the Global object */
  13. jerry_value_t global_object = jerry_get_global_object ();
  14. /* Constructing strings */
  15. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "my_var");
  16. jerry_value_t prop_value = jerry_create_string ((const jerry_char_t *) "Hello from C!");
  17. /* Setting the string value as a property of the Global object */
  18. jerry_value_t set_result = jerry_set_property (global_object, prop_name, prop_value);
  19. /* The 'set_result' should be checked if there was any error */
  20. if (jerry_value_is_error (set_result)) {
  21. printf ("Failed to add the 'my_var' property\n");
  22. }
  23. jerry_release_value (set_result);
  24. /* Releasing string values, as it is no longer necessary outside of engine */
  25. jerry_release_value (prop_name);
  26. jerry_release_value (prop_value);
  27. /* Releasing the Global object */
  28. jerry_release_value (global_object);
  29. /* Now starting script that would output value of just initialized field */
  30. jerry_value_t eval_ret = jerry_eval (script,
  31. sizeof (script) - 1,
  32. JERRY_PARSE_NO_OPTS);
  33. /* Free JavaScript value, returned by eval */
  34. jerry_release_value (eval_ret);
  35. /* Freeing engine */
  36. jerry_cleanup ();
  37. return 0;
  38. }

To compile it one can use the following command:

(Note that the libjerry-ext was added before the libjerry-port-default entry for the pkg-config call.

  1. $ gcc api-example-7.c -o api-example-7 $(pkg-config --cflags --libs libjerry-core libjerry-ext libjerry-port-default libjerry-libm)

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

  1. $ ./api-example-7

Example 8. Description of JerryScript value descriptors

JerryScript value can be a boolean, number, null, object, string, undefined or some special type of objects (arraybuffer, symbols, etc).

There is a special “error” value which wraps another value. This “error” can be created by throwing a JavaScript value from JS code or via API method(s). It is advised to check for this error with the jerry_value_is_error method as not all API methods can process error values. To extract the value from the “error” the API method jerry_get_value_from_error should be used. If an error object is created via API method (for example with jerry_create_error) the “error” value is automatically created.

Notice the difference between error value and error object:

  • The error object is a object which was constructed via one of the Error objects (available from the global object or from API). For example in JS such object be created with the following code example:
  1. var error_object = new Error ("error message");
  • The error value is not an object on its own. This is the exception raised/thrown either via API methods or from JS. For example, creating such error value in JS would look like this:
  1. throw "message";

To check what type a given jerry_value_t is the jerry_value_is_* methods or the jerry_value_get_type could be used. For example the following code snippet could print out a few types (not all types are checked):

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "jerryscript.h"
  4. static void
  5. print_value (const jerry_value_t jsvalue)
  6. {
  7. jerry_value_t value;
  8. /* If there is an error extract the object from it */
  9. if (jerry_value_is_error (jsvalue))
  10. {
  11. printf ("Error value detected: ");
  12. value = jerry_get_value_from_error (jsvalue, false);
  13. }
  14. else
  15. {
  16. value = jerry_acquire_value (jsvalue);
  17. }
  18. if (jerry_value_is_undefined (value))
  19. {
  20. printf ("undefined");
  21. }
  22. else if (jerry_value_is_null (value))
  23. {
  24. printf ("null");
  25. }
  26. else if (jerry_value_is_boolean (value))
  27. {
  28. if (jerry_get_boolean_value (value))
  29. {
  30. printf ("true");
  31. }
  32. else
  33. {
  34. printf ("false");
  35. }
  36. }
  37. /* Float value */
  38. else if (jerry_value_is_number (value))
  39. {
  40. printf ("number: %lf", jerry_get_number_value (value));
  41. }
  42. /* String value */
  43. else if (jerry_value_is_string (value))
  44. {
  45. jerry_char_t str_buf_p[256];
  46. /* Determining required buffer size */
  47. jerry_size_t req_sz = jerry_get_string_size (value);
  48. if (req_sz <= 255)
  49. {
  50. jerry_string_to_char_buffer (value, str_buf_p, req_sz);
  51. str_buf_p[req_sz] = '\0';
  52. printf ("%s", (const char *) str_buf_p);
  53. }
  54. else
  55. {
  56. printf ("error: buffer isn't big enough");
  57. }
  58. }
  59. /* Object reference */
  60. else if (jerry_value_is_object (value))
  61. {
  62. printf ("[JS object]");
  63. }
  64. printf ("\n");
  65. jerry_release_value (value);
  66. }

Example 8: 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.

See the following api-example-8-shell.c file:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "jerryscript.h"
  5. #include "jerryscript-ext/handler.h"
  6. static void
  7. print_value (const jerry_value_t jsvalue)
  8. {
  9. jerry_value_t value;
  10. /* If there is an error extract the object from it */
  11. if (jerry_value_is_error (jsvalue))
  12. {
  13. printf ("Error value detected: ");
  14. value = jerry_get_value_from_error (jsvalue, false);
  15. }
  16. else
  17. {
  18. value = jerry_acquire_value (jsvalue);
  19. }
  20. if (jerry_value_is_undefined (value))
  21. {
  22. printf ("undefined");
  23. }
  24. else if (jerry_value_is_null (value))
  25. {
  26. printf ("null");
  27. }
  28. else if (jerry_value_is_boolean (value))
  29. {
  30. if (jerry_get_boolean_value (value))
  31. {
  32. printf ("true");
  33. }
  34. else
  35. {
  36. printf ("false");
  37. }
  38. }
  39. /* Float value */
  40. else if (jerry_value_is_number (value))
  41. {
  42. printf ("number: %lf", jerry_get_number_value (value));
  43. }
  44. /* String value */
  45. else if (jerry_value_is_string (value))
  46. {
  47. jerry_char_t str_buf_p[256];
  48. /* Determining required buffer size */
  49. jerry_size_t req_sz = jerry_get_string_size (value);
  50. if (req_sz <= 255)
  51. {
  52. jerry_string_to_char_buffer (value, str_buf_p, req_sz);
  53. str_buf_p[req_sz] = '\0';
  54. printf ("%s", (const char *) str_buf_p);
  55. }
  56. else
  57. {
  58. printf ("error: buffer isn't big enough");
  59. }
  60. }
  61. /* Object reference */
  62. else if (jerry_value_is_object (value))
  63. {
  64. printf ("[JS object]");
  65. }
  66. printf ("\n");
  67. jerry_release_value (value);
  68. }
  69. int
  70. main (void)
  71. {
  72. bool is_done = false;
  73. /* Initialize engine */
  74. jerry_init (JERRY_INIT_EMPTY);
  75. /* Register 'print' function from the extensions */
  76. jerryx_handler_register_global ((const jerry_char_t *) "print",
  77. jerryx_handler_print);
  78. while (!is_done)
  79. {
  80. char cmd[256];
  81. char *cmd_tail = cmd;
  82. size_t len = 0;
  83. printf ("> ");
  84. /* Read next command */
  85. while (true)
  86. {
  87. if (fread (cmd_tail, 1, 1, stdin) != 1 && len == 0)
  88. {
  89. is_done = true;
  90. break;
  91. }
  92. if (*cmd_tail == '\n')
  93. {
  94. break;
  95. }
  96. cmd_tail++;
  97. len++;
  98. }
  99. /* If the command is "quit", break the loop */
  100. if (!strncmp (cmd, "quit\n", sizeof ("quit\n") - 1))
  101. {
  102. break;
  103. }
  104. jerry_value_t ret_val;
  105. /* Evaluate entered command */
  106. ret_val = jerry_eval ((const jerry_char_t *) cmd,
  107. len,
  108. JERRY_PARSE_NO_OPTS);
  109. /* Print out the value */
  110. print_value (ret_val);
  111. jerry_release_value (ret_val);
  112. }
  113. /* Cleanup engine */
  114. jerry_cleanup ();
  115. return 0;
  116. }

To compile it one can use the following command:

(Note that the libjerry-ext was added before the libjerry-port-default entry for the pkg-config call.

  1. $ gcc api-example-8-shell.c -o api-example-8-shell $(pkg-config --cflags --libs libjerry-core libjerry-ext libjerry-port-default libjerry-libm)

The application reads lines from standard input and evaluates them, one after another. To try out run:

  1. $ ./api-example-8-shell

Example 9. Creating JS object in global context

In this example (api-example-9.c) an object with a native function is added to the global object.

  1. #include "jerryscript.h"
  2. #include "jerryscript-ext/handler.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 (void)
  20. {
  21. /* Initialize engine */
  22. jerry_init (JERRY_INIT_EMPTY);
  23. /* Register 'print' function from the extensions */
  24. jerryx_handler_register_global ((const jerry_char_t *) "print",
  25. jerryx_handler_print);
  26. /* Do something with the native object */
  27. my_struct.msg = "Hello, World!";
  28. /* Create an empty JS object */
  29. jerry_value_t object = jerry_create_object ();
  30. /* Create a JS function object and wrap into a jerry value */
  31. jerry_value_t func_obj = jerry_create_external_function (get_msg_handler);
  32. /* Set the native function as a property of the empty JS object */
  33. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "myFunc");
  34. jerry_release_value (jerry_set_property (object, prop_name, func_obj));
  35. jerry_release_value (prop_name);
  36. jerry_release_value (func_obj);
  37. /* Wrap the JS object (not empty anymore) into a jerry api value */
  38. jerry_value_t global_object = jerry_get_global_object ();
  39. /* Add the JS object to the global context */
  40. prop_name = jerry_create_string ((const jerry_char_t *) "MyObject");
  41. jerry_release_value (jerry_set_property (global_object, prop_name, object));
  42. jerry_release_value (prop_name);
  43. jerry_release_value (object);
  44. jerry_release_value (global_object);
  45. /* Now we have a "builtin" object called MyObject with a function called myFunc()
  46. *
  47. * Equivalent JS code:
  48. * var MyObject = { myFunc : function () { return "some string value"; } }
  49. */
  50. const jerry_char_t script[] = " \
  51. var str = MyObject.myFunc (); \
  52. print (str); \
  53. ";
  54. /* Evaluate script */
  55. jerry_value_t eval_ret = jerry_eval (script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
  56. /* Free JavaScript value, returned by eval */
  57. jerry_release_value (eval_ret);
  58. /* Cleanup engine */
  59. jerry_cleanup ();
  60. return 0;
  61. }

To compile it one can use the following command:

(Note that the libjerry-ext was added before the libjerry-port-default entry for the pkg-config call.

  1. $ gcc api-example-9.c -o api-example-9 $(pkg-config --cflags --libs libjerry-core libjerry-ext libjerry-port-default libjerry-libm)

Execute the example with:

  1. $ ./api-example-9

The application will generate the following output:

  1. Hello, World

Example 10. Extending JS Objects with native functions

The example creates a JS Object with jerry_eval, then it is extended from C with a native function. In addition this native function shows how to get a property value from the object and how to manipulate it.

Use the following code for api-example-10.c:

  1. #include "jerryscript.h"
  2. #include "jerryscript-ext/handler.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. /* The the 'this_val' is the 'MyObject' from the JS code below */
  13. /* Note: that the argument count check is ignored for the example's case */
  14. /* Get 'this.x' */
  15. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "x");
  16. jerry_value_t x_val = jerry_get_property (this_val, prop_name);
  17. if (!jerry_value_is_error (x_val))
  18. {
  19. /* Convert Jerry API values to double */
  20. double x = jerry_get_number_value (x_val);
  21. double d = jerry_get_number_value (args_p[0]);
  22. /* Add the parameter to 'x' */
  23. jerry_value_t res_val = jerry_create_number (x + d);
  24. /* Set the new value of 'this.x' */
  25. jerry_release_value (jerry_set_property (this_val, prop_name, res_val));
  26. jerry_release_value (res_val);
  27. }
  28. jerry_release_value (x_val);
  29. jerry_release_value (prop_name);
  30. return jerry_create_undefined ();
  31. } /* add_handler */
  32. int
  33. main (void)
  34. {
  35. /* Initialize engine */
  36. jerry_init (JERRY_INIT_EMPTY);
  37. /* Register 'print' function from the extensions */
  38. jerryx_handler_register_global ((const jerry_char_t *) "print",
  39. jerryx_handler_print);
  40. /* Create a JS object */
  41. const jerry_char_t my_js_object[] = " \
  42. MyObject = \
  43. { x : 12, \
  44. y : 'Value of x is ', \
  45. foo: function () \
  46. { \
  47. return this.y + this.x; \
  48. } \
  49. } \
  50. ";
  51. jerry_value_t my_js_obj_val;
  52. /* Evaluate script */
  53. my_js_obj_val = jerry_eval (my_js_object,
  54. sizeof (my_js_object) - 1,
  55. JERRY_PARSE_NO_OPTS);
  56. /* Create a JS function object and wrap into a jerry value */
  57. jerry_value_t add_func_obj = jerry_create_external_function (add_handler);
  58. /* Set the native function as a property of previously created MyObject */
  59. jerry_value_t prop_name = jerry_create_string ((const jerry_char_t *) "add2x");
  60. jerry_release_value (jerry_set_property (my_js_obj_val, prop_name, add_func_obj));
  61. jerry_release_value (add_func_obj);
  62. jerry_release_value (prop_name);
  63. /* Free JavaScript value, returned by eval (my_js_object) */
  64. jerry_release_value (my_js_obj_val);
  65. const jerry_char_t script[] = " \
  66. var str = MyObject.foo (); \
  67. print (str); \
  68. MyObject.add2x (5); \
  69. print (MyObject.foo ()); \
  70. ";
  71. /* Evaluate script */
  72. jerry_value_t eval_ret = jerry_eval (script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
  73. /* Free JavaScript value, returned by eval */
  74. jerry_release_value (eval_ret);
  75. /* Cleanup engine */
  76. jerry_cleanup ();
  77. return 0;
  78. }

To compile it one can use the following command:

(Note that the libjerry-ext was added before the libjerry-port-default entry for the pkg-config call.

  1. $ gcc api-example-10.c -o api-example-10 $(pkg-config --cflags --libs libjerry-core libjerry-ext libjerry-port-default libjerry-libm)

Execute the example with:

  1. $ ./api-example-10
  1. Value of x is 12
  2. Value of x is 17

Example 11. Changing the seed of pseudorandom generated numbers

If you want to change the seed of Math.random() generated numbers, you have to initialize the seed value with srand. A recommended method is using jerry_port_get_current_time() or something based on a constantly changing value, therefore every run produces truly random numbers.

  1. #include <stdlib.h>
  2. #include "jerryscript.h"
  3. #include "jerryscript-port.h"
  4. #include "jerryscript-ext/handler.h"
  5. int
  6. main (void)
  7. {
  8. /* Initialize srand value */
  9. srand ((unsigned) jerry_port_get_current_time ());
  10. /* Generate a random number, and print it */
  11. const jerry_char_t script[] = "var a = Math.random (); print(a)";
  12. /* Initialize the engine */
  13. jerry_init (JERRY_INIT_EMPTY);
  14. /* Register the print function */
  15. jerryx_handler_register_global ((const jerry_char_t *) "print",
  16. jerryx_handler_print);
  17. /* Evaluate the script */
  18. jerry_value_t eval_ret = jerry_eval (script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
  19. /* Free the JavaScript value returned by eval */
  20. jerry_release_value (eval_ret);
  21. /* Cleanup the engine */
  22. jerry_cleanup ();
  23. return 0;
  24. }

Further steps

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