JSAPI Cookbook

This article is in need of a technical review.

This article shows the JSAPI equivalent for a tiny handful of common JavaScript idioms.

Note: The FOSS wiki page contains a few links to other libraries and programs that can make life easier when using SpiderMonkey and JSAPI.

Basics

Finding the global object

Many of these recipes require finding the current global object first.

// JavaScript
var global = this;

There is a function, JS_GetGlobalForScopeChain(cx), that makes a best guess, and sometimes that is the best that can be done. But in a JSNative the correct way to do this is:

/* JSAPI */
JSBool myNative(JSContext *cx, uintN argc, jsval *vp)
{
    CallArgs args = CallArgsFromVp(argc, vp);
    JSObject *global = JS_GetGlobalForObject(cx, &args.callee());
    ...
}

Defining a function

// JavaScript
function justForFun() {
    return null;
}
/* JSAPI */
JSBool justForFun(JSContext *cx, uintN argc, jsval *vp)
{
    JS_SET_RVAL(cx, vp, JSVAL_NULL);
    return JS_TRUE;
}

...

/*
 * Add this to your JSContext setup code.
 * This makes your C function visible as a global function in JavaScript.
 */
if (!JS_DefineFunction(cx, global, "justForFun", &justForFun, 0, 0))
    return JS_FALSE;

To define many JSAPI functions at once, use JS_DefineFunctions.

Creating an Array

// JavaScript
var x = [];  // or "x = Array()", or "x = new Array"
/* JSAPI */
JSObject *x = JS_NewArrayObject(cx, 0, NULL);
if (x == NULL)
    return JS_FALSE;

Creating an Object

// JavaScript
var x = {};  // or "x = Object()", or "x = new Object"
/* JSAPI */
JSObject *x = JS_NewObject(cx, NULL, NULL, NULL);
if (x == NULL)
    return JS_FALSE;

Constructing an object with new

// JavaScript
var person = new Person("Dave", 24);

It looks so simple in JavaScript, but a JSAPI application has to do three things here:

  • look up the constructor, Person
  • prepare the arguments ("Dave", 24)
  • call JS_New to simulate the new keyword

(If your constructor doesn't take any arguments, you can skip the second step and call JS_New(cx, constructor, 0, NULL) in step 3.)

/* JSAPI */

jsval constructor_val;
JSObject *constructor; /* BUG - not rooted */
JSString *name_str;
jsval argv[2];  /* BUG - not rooted */
JSObject *obj;

/* Step 1 - Get the value of |Person| and check that it is an object. */
if (!JS_GetProperty(cx, JS_GetGlobalObject(cx), "Person", &constructor_val))
    return JS_FALSE;
if (JSVAL_IS_PRIMITIVE(constructor_val)) {
    JS_ReportError(cx, "Person is not a constructor");
    return JS_FALSE;
}
constructor = JSVAL_TO_OBJECT(constructor_val);

/* Step 2 - Set up the arguments. */
name_str = JS_NewStringCopyZ(cx, "Dave");
if (!name_str)
    return JS_FALSE;
argv[0] = STRING_TO_JSVAL(name_str);
argv[1] = INT_TO_JSVAL(24);

/* Step 3 - Call |new Person(...argv)|, passing the arguments. */
obj = JS_New(cx, constructor, 2, argv);
if (!obj)
    return JS_FALSE;

Calling a global JS function

// JavaScript
var r = foo();  // where f is a global function
/* JSAPI
 *
 * Suppose the script defines a global JavaScript
 * function foo() and we want to call it from C.
 */
jsval r;
if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
   return JS_FALSE;

Calling a JS function via a local variable

// JavaScript
var r = f();  // where f is a local variable
/* JSAPI
 *
 * Suppose f is a local C variable of type jsval.
 */
jsval r;
if (!JS_CallFunctionValue(cx, NULL, f, 0, NULL, &r)
    return JS_FALSE;

Returning an integer

// JavaScript
return 23;
/* JSAPI
 *
 * Warning: This only works for integers that fit in 32 bits.
 * Otherwise, convert the number to floating point (see the next example).
 */
JS_SET_RVAL(cx, vp, INT_TO_JSVAL(23));
return JS_TRUE;

Returning a floating-point number

// JavaScript
return 3.14159;
/* JSAPI */
jsdouble n = 3.14159;
return JS_NewNumberValue(cx, n, rval);

Exception handling

throw

The most common idiom is to create a new Error object and throw that. JS_ReportError does this. Note that JavaScript exceptions are not the same thing as C++ exceptions. The JSAPI code also has to return JS_FALSE to signal failure to the caller.

// JavaScript
throw new Error("Failed to grow " + varietal + ": too many greenflies.");
/* JSAPI */
JS_ReportError(cx, "Failed to grow %s: too many greenflies.", varietal);
return JS_FALSE;

To internationalize your error messages, and to throw other error types, such as SyntaxError or TypeError, use JS_ReportErrorNumber instead.

JavaScript also supports throwing any value at all, not just Error objects. Use JS_SetPendingException to throw an arbitrary jsval from C/C++.

// JavaScript
throw exc;
/* JSAPI */
JS_SetPendingException(cx, exc);
return JS_FALSE;

When JS_ReportError creates a new Error object, it sets the fileName and lineNumber properties to the line of JavaScript code currently at the top of the stack. This is usually the line of code that called your native function, so it's usually what you want. JSAPI code can override this by creating the Error object directly and passing additional arguments to the constructor:

// JavaScript
throw new Error(message, filename, lineno);
/* JSAPI */
JSBool ThrowError(JSContext *cx, JSObject *global,
                  const char *message, const char *filename, int32 lineno)
{
    JSString *messageStr;
    JSString *filenameStr;
    jsval args[3];
    jsval exc;

    messageStr = JS_NewStringCopyZ(cx, message);
    if (!messageStr)
        return JS_FALSE;
    filenameStr = JS_NewStringCopyZ(cx, filename);
    if (!filenameStr)
        return JS_FALSE;

    args[0] = STRING_TO_JSVAL(messageStr);
    args[1] = STRING_TO_JSVAL(filenameStr);
    args[2] = INT_TO_JSVAL(lineno);
    if (JS_CallFunctionName(cx, global, "Error", 3, args, &exc))
        JS_SetPendingException(cx, exc);
    return JS_FALSE;
}

...

return ThrowError(cx, global, message, __FILE__, __LINE__);

The JSAPI code here is actually simulating throw Error(message) without the new, as new is a bit harder to simulate using the JSAPI. In this case, unless the script has redefined Error, it amounts to the same thing.

catch

// JavaScript
try {
    // try some stuff here; for example:
    foo();
    bar();
} catch (exc) {
    // do error-handling stuff here
}
/* JSAPI */
    jsval exc;

    /* try some stuff here; for example: */
    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
        goto catch_block;  /* instead of returning JS_FALSE */
    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
        goto catch_block;  /* instead of returning JS_FALSE */
    return JS_TRUE;

catch_block:
    if (!JS_GetPendingException(cx, &exc))
        return JS_FALSE;
    JS_ClearPendingException(cx);
    /* do error-handling stuff here */
    return JS_TRUE;

finally

// JavaScript
try {
   foo();
   bar();
} finally {
   cleanup();
}

If your C/C++ cleanup code doesn't call back into the JSAPI, this is straightforward:

/* JSAPI */
    JSBool success = JS_FALSE;

    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
        goto finally_block;  /* instead of returning JS_FALSE immediately */
    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
        goto finally_block;
    success = JS_TRUE;
    /* Intentionally fall through to the finally block. */

finally_block:
    cleanup();
    return success;

However, if cleanup() is actually a JavaScript function, there's a catch. When an error occurs, the JSContext's pending exception is set. If this happens in foo() or bar() in the above example, the pending exception will still be set when you call cleanup(), which would be bad. To avoid this, your JSAPI code implementing the finally block must:

  • save the old exception, if any
  • clear the pending exception so that your cleanup code can run
  • do your cleanup
  • restore the old exception, if any
  • return JS_FALSE if an exception occurred, so that the exception is propagated up.
/* JSAPI */
    JSBool success = JS_FALSE;
    JSExceptionState *exc_state;

    if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r))
        goto finally_block;  /* instead of returning JS_FALSE immediately */
    if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r))
        goto finally_block;
    success = JS_TRUE;
    /* Intentionally fall through to the finally block. */

finally_block:
    exc_state = JS_SaveExceptionState(cx);
    if (exc_state == NULL)
        return JS_FALSE;
    JS_ClearPendingException(cx);

    if (!JS_CallFunctionName(cx, global, "cleanup", 0, NULL, &r)) {
        /* The new error replaces the previous one, so discard the saved exception state. */
        JS_DropExceptionState(cx, exc_state);
        return JS_FALSE;
    }
    JS_RestoreExceptionState(cx, exc_state);
    return success;

Object properties

Getting a property

// JavaScript
var x = y.myprop;

The JSAPI function that does this is JS_GetProperty. It requires a JSObject * argument. Since JavaScript values are usually stored in jsval variables, a cast or conversion is usually needed.

In cases where it is certain that y is an object (that is, not a boolean, number, string, null, or undefined), this is fairly straightforward. Use JSVAL_TO_OBJECT to cast y to type JSObject *.

/* JSAPI */
jsval x;

assert(!JSVAL_IS_PRIMITIVE(y)); 
if (!JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
    return JS_FALSE;

That code will crash if y is not an object. That's often unacceptable. An alternative would be to simulate the behavior of the JavaScript . notation exactly. It's a nice thought—JavaScript wouldn't crash, at least—but implementing its exact behavior turns out to be quite complicated, and most of the work is not particularly helpful.

Usually it is best to check for !JSVAL_IS_PRIMITIVE(y) and throw an Error with a nice message.

/* JSAPI */
jsval x;

if (JSVAL_IS_PRIMITIVE(y))
    return ThrowError(cx, global, "Parameter y must be an object.", __FILE__, __LINE__);  /* see the #throw example */
if (!JS_GetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
    return JS_FALSE;

Setting a property

// JavaScript
y.myprop = x;

See "Getting a property", above, concerning the case where y is not an object.

/* JSAPI */
assert(!JSVAL_IS_PRIMITIVE(y));
if (!JS_SetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
    return JS_FALSE;

Checking for a property

// JavaScript
if ("myprop" in y) {
    // then do something
}

See "Getting a property", above, concerning the case where y is not an object.

/* JSAPI */
JSBool found;

assert(!JSVAL_IS_PRIMITIVE(y));
if (!JS_HasProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &found))
    return JS_FALSE;
if (found) {
    // then do something
}

Defining a constant property

This is the first of three examples involving the built-in function Object.defineProperty(), which gives JavaScript code fine-grained control over the behavior of individual properties of any object.

You can use this function to create a constant property, one that can't be overwritten or deleted. Specify writable: false to make the property read-only and configurable: false to prevent it from being deleted or redefined. The flag enumerable: true causes this property to be seen by for-in loops.

// JavaScript
Object.defineProperty(obj, "prop", {value: 123,
                                    writable: false,
                                    enumerable: true,
                                    configurable: false});

The analogous JSAPI function is JS_DefineProperty. The property attribute JSPROP_READONLY corresponds to writeable: false, JSPROP_ENUMERATE to enumerable: true, and JSPROP_PERMANENT to configurable: false. To get the opposite behavior for any of these settings, simply omit the property attribute bits you don't want.

/* JSAPI */
if (!JS_DefineProperty(cx, obj, "prop", INT_TO_JSVAL(123),
                       JS_PropertyStub, JS_StrictPropertyStub,
                       JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT)) {
   return JS_FALSE;
}

Defining a property with a getter and setter

Object.defineProperty() can be used to define properties in terms of two accessor functions.

// JavaScript
Object.defineProperty(obj, "prop", {get: GetPropFunc,
                                    set: SetPropFunc,
                                    enumerable: true});

In the JSAPI version, GetPropFunc and SetPropFunc are C/C++ functions of type JSNative.

/* JSAPI */
if (!JS_DefineProperty(cx, obj, "prop", JSVAL_VOID,
                       (JSPropertyOp) GetPropFunc, (JSStrictPropertyOp) SetPropFunc,
                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE)) {
    return JS_FALSE;
}

Defining a read-only property with only a getter

// JavaScript
Object.defineProperty(obj, "prop", {get: GetPropFunc,
                                    enumerable: true});

In the JSAPI version, to signify that the property is read-only, pass NULL for the setter.

/* JSAPI */
if (!JS_DefineProperty(cx, obj, "prop", JSVAL_VOID,
                       GetPropFunc, NULL,
                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE)) {
    return JS_FALSE;
}

Working with the prototype chain

Defining a native read-only property on the String.prototype

// JavaScript
Object.defineProperty(String.prototype, "md5sum", {get: GetMD5Func,
                                                   enumerable: true});	

The following trick couldn't work if someone has replaced the global String object with something.

/* JSAPI */
JSObject   *string, *string_prototype;
jsval       val;

// Get the String constructor from the global object.
if (!JS_GetProperty(cx, global, "String", &val))
    return JS_FALSE;
if (JSVAL_IS_PRIMITIVE(val))
    return ThrowError(cx, global, "String is not an object", __FILE__, __LINE__);
string = JSVAL_TO_OBJECT(val);

// Get String.prototype.
if (!JS_GetProperty(cx, string, "prototype", &val))
    return JS_FALSE;
if (JSVAL_IS_PRIMITIVE(val))
    return ThrowError(cx, global, "String.prototype is not an object", __FILE__, __LINE__);
string_prototype = JSVAL_TO_OBJECT(val);

// ...and now we can add some new functionality to all strings.
if (!JS_DefineProperty(cx, string_prototype, "md5sum", JSVAL_VOID, GetMD5Func, NULL,
                       JSPROP_SHARED | JSPROP_NATIVE_ACCESSORS | JSPROP_ENUMERATE))
    return JS_FALSE;

Wanted

  • Simulating for and for each.
  • Actually outputting errors.
  • Create global variable __dirname to retrieve the current JavaScript file name, like in NodeJS

Document Tags and Contributors

Contributors to this page: mvel, JPEG, MrN, berkerpeksag, atrauzzi, meh., EricT, Jorend, Norbert
Last updated by: EricT,