Visit Mozilla.org

JSAPI Phrasebook

From MDC

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

Contents

[edit] Basics

[edit] Defining a function

// JavaScript
function justForFun() {
    return null;
}
/* JSAPI */
JSBool justForFun(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
   *rval = 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, JS_GetGlobalObject(cx), "justForFun", &justForFun, 0, 0))
    return JS_FALSE;

To define many JSAPI functions at once, use JS_DefineFunctions.

[edit] 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;

[edit] 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;

[edit] 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;

[edit] 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;

[edit] Returning an integer

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

[edit] Returning a floating-point number

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

[edit] Exception handling

[edit] throw

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

The usual idiom involves creating a new exception object and throwing that:

// JavaScript
throw new Error(message);
/* JSAPI */
jsval exc;

if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "Error", 1, &message, &exc))
    return JS_FALSE;
JS_SetPendingException(cx, exc);
return JS_FALSE;

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

[edit] 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, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
        goto catch_block;  /* instead of returning JS_FALSE */
    if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "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;

[edit] 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, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
        goto finally_block;  /* instead of returning JS_FALSE immediately */
    if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "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, JS_GetGlobalObject(cx), "foo", 0, NULL, &r))
        goto finally_block;  /* instead of returning JS_FALSE immediately */
    if (!JS_CallFunctionName(cx, JS_GetGlobalObject(cx), "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, JS_GetGlobalObject(cx), "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;

[edit] Object properties

[edit] Getting a property

// JavaScript
var x = y.myprop;

The JSAPI function that does this is JS_GetProperty. It requires a JSObject * argument. Since JavaScript variables are stored in usually jsval variables, a cast or conversion is 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_OBJECT(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_OBJECT(y) and throw a TypeError with a nice error message.


[edit] 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_OBJECT(y));
if (!JS_SetProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &x))
    return JS_FALSE;

[edit] 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_OBJECT(y));
if (!JS_HasProperty(cx, JSVAL_TO_OBJECT(y), "myprop", &found))
    return JS_FALSE;
if (found) {
    // then do something
}

[edit] Wanted

  • Using JS_GetStandardClass in the throw new Error example, so it throws an actual Error even if the program has deleted or assigned to the global property Error.
  • Simulating for and for each.
  • Calling a constructor with new.