The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

JS::Context - An object in which we can execute javascript

SYNOPSIS

use JS;

my $ctx = JS::Runtime->new->create_context();

# Add a function callable from javascript
$ctx->bind_function(print => sub { print @_; });

my $result = $ctx->eval($javascript_source);

DESCRIPTION

To interact with the SpiderMonkey javascript engine you need a JS::Context instance. To create one you can use the method "create_context" in JS::Runtime or obtain a "stock" one with "stock_context" in JS.

INTERFACE

CLASS METHODS

There are available the following class methods

find ( $ContextId )

Returns the JS::Context object associated with a given $ContextId if exists or undef if not.

See "id".

current ( )

Returns the current JS::Context object.

To be used by perl subroutines designed to be called by javascript land when they need the context with in they are being called.

When there aren't an active context, it dies with the error "Not in a javascript context".

INSTANCE METHODS

get_global ( )

Returns the global object associated with the JS context, equivalent to $ctx->eval('this')

new_object ( )

Returns a newly born javascript object. This is equivalent to $ctx->eval('({})')

get_controller ( )

Returns the Javascript::Controller controller associated with the JS context.

bind_value ( $path => $value )

Defines a property with a given $name and $value.

$path is a string that reference a property in the global object or a path to deep properties, creating empty Objects for any missing.

For example:

$ctx->bind_value('foo' => $value); # Set 'foo' to $value

$ctx->bind_value('foo.bar' => $value); # Create 'foo' as '{}' if needed
                                       # and set 'foo.bar' to $value

Trying to redefine an already existing property throws an exception, i.e. the last component of $name must not exists.

Returns $value

bind_object ( $path => $value )

The same as bind_value above, but check that $value is an object (i.e. a blessed reference), and throws otherwise.

bind_function ( name => $path, func => $subroutine )
bind_function ( $path => $subroutine )

Defines a Perl subroutine as a native function with the given $path. The argument $subroutine can either be the name of a subroutine or a reference to one.

The four arguments form should not be used in new code as can be deprecated in the future.

bind_all ( $name1 => $value1, ... )

Calls bind_value above for every pair of its arguments. Allowing you to mass populate the context.

unbind_value ( $name )

Remove a property from the context or a specified object.

call ( $name, @arguments )
call ( $function, @arguments )

Calls the function named $name or the JS::Function-object $function and passes the rest of the arguments to the javascript function.

can ( $name )

Check if in the context there is a function with a given $name. Returns a reference to the function if there otherwise returns undef.

The return value, if TRUE, can be called:

    if(my $date = $ctx->can('Date')) { # 'Date' is there
	print $date->(time * 1000); # Now
    }
compile ( $source )

Compiles the javascript code given in $source, and returns a JS::Script instance that can be executed over and over again without paying the compilation overhead every time.

If a compilation error occurs returns undef and sets $@.

compile_file ( $file_name )

Compiles the javascript code in $file_name, returns a JS::Script instance that can be executed over and over again without paying the compilation overhead every time.

If a compilation error occurs returns undef and sets $@.

eval ( $source )

Evaluates the javascript code given in $source and returns the result from the last statement.

eval_file ( $path )

Evaluates the javascript code in the file specified by $path and returns the result from the last statement.

If there is a compilation error (such as a syntax error) or an uncaught exception is thrown in javascript this method returns undef and $@ is set.

bind_class ( $jsclass )

Bind a native class created "with JS::PerlClass"

check_privileges ( )

To be used inside perl code called from javascript. Check that the context isn't restricted, otherwise dies with the error "Not enought privileges";

set_branch_handler ( $handler )

Attaches an branch callback handler (a function that is called when a branch is performed) to the context. The argument $handler may be a code-reference or the name of a subroutine.

To remove the handler call this method with an undefined argument.

The handler is called when a script branches backwards during execution, when a function returns and the end of the script. To continue execution the handler must return a true value. To abort execution either throw an exception or return a false value.

id ( )

Returns the "Context ID" of the calling context. Every context has an integer associated with it that can be used to identify a particular context.

See "find".

get_version ( )

Returns the runtime version of the context as a string, for example 1.7 or or ECMAv3.

set_version ( $version )

Sets the runtime version of the context to that specified in the string $version. Some features such as let and yield might not be enabled by default and thus must be turned on by specifying what JS version we're using.

A list of these can be found at http://developer.mozilla.org/en/docs/JSVersion but may vary depending on the version of your runtime.

Context options

There are a few options that change the operation of the context, those can be manipulated using the context handle as a HASH reference, all options are booleans so any value setted will be TRUE or FALSE as by perl rules and can be made local for temporarilly changes.

{
  local $ctx->{OptionFoo} = 1;
  # This code uses a TRUE OptionFoo;
  ...
}
# From here, OptionFoo uses its previous value
...

The currently defined options are:

AutoTie

If TRUE the wrapped instances of Array and Object, when returned to perl will be automatically tied in real perl HASHes and ARRAYs so you perl code will not see instances of JS::Object or JS::Array unless you explicitly use the tied perl function.

When FALSE the wrapper instances will be returned directly.

The default value is TRUE

ConstantsValue

If TRUE "Constant Functions" in perlsub defined in perl namespaces, when reflected to javascript will be seen as true constants values. When FALSE they will be seen as normal functions, so to obtain its values they must be called.

The default value is TRUE

ConvertRegExp

If TRUE all instances of javascript RegExp will be converted to perl RegExp, when FALSE they will be wrapped in instances on JS::Object in the normal way.

The default value is TRUE

RaiseExceptions

When TRUE all untrapped exceptions in javascript space will raise a perl fatal exception. Set to FALSE to revert to the behavior of previous versions that only set $@ and returns undef.

The default value is TRUE

StrictEnable

Warn on dubious practice. Defaults to FALSE.

XMLEnable

In E4X (ECMAScript for XML) parse <!-- --> as a token. Defaults to TRUE.

JITEnable

Enable JIT compilation. Requires a SpiderMonkey with TraceMonkey. Defaults to FALSE.