javascriptcore

package module
v0.0.0-...-b493969 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2012 License: BSD-3-Clause Imports: 4 Imported by: 2

README

This is the source code repository for javascriptcore-go, a wrapper of
the JavaScriptCore library for use with Go.  In addition to providing 
access to the library, this wrapper allows callers to easily reflect 
native functions and objects from Go into the scripting environment.

The canonical repository is located at:
http://bitbucket.org/rj/javascriptcore-go

Documentation

Overview

This package is a wrapper for JavaScriptCore, which is the JavaScript engine used by the WebKit web browser engine. In addition to providing access to the library, this wrapper allows callers to easily reflect native functions and objects from Go into the scripting environment.

For a complete description of the library, and the purpose and use of the JavaScriptCore API, please refer to the WebKit documentation.

As an example use of the library:

func main() {
	ctx := js.NewContext()
	defer ctx.Release()

	ret, err := ctx.EvaluateScript("function test() { return 1;}; test()", nil, "./fake.js", 1)
	if err != nil {
		fmt.Println( "EvaluateScript raised an error (", err, ")" )
	} else if ret == nil {
		fmt.Println("EvaluateScript failed to return a result")
	} else {
		stringval := ctx.ToStringOrDie(ret)
		fmt.Println("EvaluateScript returned a result: ", stringval )
	}
}

Index

Examples

Constants

View Source
const (
	TypeUndefined = Kind(0)    // The unique undefined value.
	TypeNull      = Kind(iota) // The unique null value.
	TypeBoolean   = Kind(iota) // The value contains a boolean.
	TypeNumber    = Kind(iota) // The value contains a number.
	TypeString    = Kind(iota) // The value contains a string.
	TypeObject    = Kind(iota) // The value contains an object.
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// contains filtered or unexported fields
}

A Context holds the state and the global object for execution of JavaScript code.

func (*Context) CallAsConstructor

func (ctx *Context) CallAsConstructor(obj *Object, parameters []*Value) (val *Object, err *Value)

func (*Context) CallAsFunction

func (ctx *Context) CallAsFunction(obj *Object, thisObject *Object, parameters []*Value) (val *Value, err *Value)

func (*Context) CheckScriptSyntax

func (ctx *Context) CheckScriptSyntax(script string, source_url string, startingLineNumber int) *Value

CheckScriptSyntax checks for syntax errors in a string of JavaScript

func (*Context) CopyPropertyNames

func (ctx *Context) CopyPropertyNames(obj *Object) *PropertyNameArray

func (*Context) DeleteProperty

func (ctx *Context) DeleteProperty(obj *Object, name string) (bool, *Value)

func (*Context) EvaluateScript

func (ctx *Context) EvaluateScript(script string, thisObject *Object, source_url string, startingLineNumber int) (value *Value, error *Value)

EvaluateScript evaluates a string of JavaScript. If the script is well-formed, and executes without error, then the result of evaluating the JavaScript code will be returned. Otherwise, an JavaScript error object will be returned.

Example
ctx := NewGlobalContext()
defer ctx.Release()

ret, err := ctx.EvaluateScript("function test() { return 1;}; test()", nil, "./fake.js", 1)
if err != nil {
	fmt.Println("EvaluateScript raised an error (", err, ")")
} else if ret == nil {
	fmt.Println("EvaluateScript failed to return a result")
} else {
	stringval := ctx.ToStringOrDie(ret)
	fmt.Println("EvaluateScript returned a result: ", stringval)
}
Output:

EvaluateScript returned a result:  1

func (*Context) GarbageCollect

func (ctx *Context) GarbageCollect()

GarbageCollects initiates garbage collection of the values and objects in a context.

func (*Context) GetProperty

func (ctx *Context) GetProperty(obj *Object, name string) (val *Value, err *Value)

func (*Context) GetPropertyAtIndex

func (ctx *Context) GetPropertyAtIndex(obj *Object, index uint16) (val *Value, err *Value)

func (*Context) GetPrototype

func (ctx *Context) GetPrototype(obj *Object) *Value

func (*Context) GlobalObject

func (ctx *Context) GlobalObject() *Object

GlobalObject returns the global object associated with an JavaScript execution context.

func (*Context) HasProperty

func (ctx *Context) HasProperty(obj *Object, name string) bool

func (*Context) IsBoolean

func (ctx *Context) IsBoolean(v *Value) bool

IsBoolean returns true if the value has type boolean.

func (*Context) IsConstructor

func (ctx *Context) IsConstructor(obj *Object) bool

func (*Context) IsEqual

func (ctx *Context) IsEqual(a *Value, b *Value) (eq bool, err *Value)

func (*Context) IsFunction

func (ctx *Context) IsFunction(obj *Object) bool

func (*Context) IsNull

func (ctx *Context) IsNull(v *Value) bool

IsNull returns true if the value has type null.

func (*Context) IsNumber

func (ctx *Context) IsNumber(v *Value) bool

IsNumber returns true if the value has type number.

func (*Context) IsObject

func (ctx *Context) IsObject(v *Value) bool

IsObject returns true if the value has type object.

func (*Context) IsStrictEqual

func (ctx *Context) IsStrictEqual(a *Value, b *Value) bool

func (*Context) IsString

func (ctx *Context) IsString(v *Value) bool

IsString returns true if the value has type string.

func (*Context) IsUndefined

func (ctx *Context) IsUndefined(v *Value) bool

IsUndefined returns true if the value has type undefined.

func (*Context) Kind

func (ctx *Context) Kind(v *Value) Kind

Kind return the type of the JavaScript value. See the type Kind.

func (*Context) NewArray

func (ctx *Context) NewArray(items []*Value) (arr *Object, err *Value)

func (*Context) NewBooleanValue

func (ctx *Context) NewBooleanValue(value bool) *Value

NewBooleanValue creates a new JavaScript boolean value, and returns a reference to the new value.

func (*Context) NewDate

func (ctx *Context) NewDate() (date *Object, err *Value)

func (*Context) NewDateWithMilliseconds

func (ctx *Context) NewDateWithMilliseconds(milliseconds float64) (date *Object, err *Value)

func (*Context) NewDateWithString

func (ctx *Context) NewDateWithString(date string) (obj *Object, err *Value)

func (*Context) NewError

func (ctx *Context) NewError(message interface{}) (obj *Object, err *Value)

func (*Context) NewErrorFromString

func (ctx *Context) NewErrorFromString(message string) (obj *Object, err *Value)

func (*Context) NewFunction

func (ctx *Context) NewFunction(name string, parameters []string, body string, source_url string, starting_line_number int) (fn *Object, err *Value)
Example
ctx := NewGlobalContext()
defer ctx.Release()

fn, err := ctx.NewFunction("myfun", []string{"a", "b"}, "return a+b;", "./testing.go", 1)
if err != nil {
	fmt.Println("Failed to create function.")
}
fmt.Println("New value tests as a function?", ctx.IsFunction(fn))
Output:

New value tests as a function? true

func (*Context) NewFunctionWithCallback

func (ctx *Context) NewFunctionWithCallback(callback GoFunctionCallback) *Object

NewFunctionWithCallback creates a new JavaScript function object that can be called from within the JavaScript context. The JavaScript function's behaviour is implemented using a generic callback inside of Go.

Unlike wraping native methods directly, a JavaScript function created using a callback is capable of handling any mixture of valid JavaScript values as parameters, and can exhibit polymorphic behaviour.

The callback can panic. If the callback panics, the value thrown is converted using the method NewError using the Context. The resulting JavaScript value is then thrown within the JavaScript context.

See also NewFunctionWithNative.

func (*Context) NewFunctionWithNative

func (ctx *Context) NewFunctionWithNative(fn interface{}) *Object

NewFunctionWithNative creates a new JavaScript function object that can be called from within the JavaScript context. The JavaScript function's behaviour is implemented by wrapping a native Go function or closure, and coercing JavaScript values as required.

For compatibility with JavaScript, the function or closure must return either zero or one parameters. Any additional return parameters will be ignored when returning the results to JavaScript. See the method NewValue of the type Context for information about type conversions for the returned value.

The function can panic. If the function panics, the value throw is converted using the method NewError using the Context. The resulting JavaScript value is then thrown within the JavaScript context.

See also NewFunctionWithCallback.

Example
// Create the execution context
ctx := NewGlobalContext()
defer ctx.Release()

// Wrap a callback and add it to the global object
fn := func() {
	fmt.Println("Hello from Go from JavaScript!")
}
val := ctx.NewFunctionWithNative(fn)
err := ctx.SetProperty(ctx.GlobalObject(), "gofunc", val.ToValue(), 0)
if err != nil {
	panic(err)
}

// Run a script that will call back into Go.
_, err = ctx.EvaluateScript("gofunc()", nil, "./fake.js", 1)
if err != nil {
	panic(err)
}
Output:

Hello from Go from JavaScript!

func (*Context) NewNativeObject

func (ctx *Context) NewNativeObject(obj interface{}) *Object

NewNativeObject creates a new JavaScript object that wraps a native Go structure or a pointer to a structure. The structures fields and methods will be accessible from within the JavaScript context. If wrapping a pointer to a structure, then changes made in JavaScript will be visible in Go.

If the argument is a pointer to a structure, than updates to the structure's fields within JavaScript will also be visible within Go.

The structure's methods can be called from from within JavaScript. The methods act according to the same rules as NewFunctionWithNative.

func (*Context) NewNullValue

func (ctx *Context) NewNullValue() *Value

NewNullValue creates a new JavaScript value of the null type, and returns a reference to the new value.

func (*Context) NewNumberValue

func (ctx *Context) NewNumberValue(value float64) *Value

NewNumberValue creates a new JavaScript number value, and returns a reference to the new value.

func (*Context) NewObject

func (ctx *Context) NewObject() *Object

func (*Context) NewRegExp

func (ctx *Context) NewRegExp(regex string) (re *Object, err *Value)

func (*Context) NewRegExpFromValues

func (ctx *Context) NewRegExpFromValues(parameters []*Value) (re *Object, err *Value)

func (*Context) NewString

func (ctx *Context) NewString(value string) *Value

NewString creates a new JavaScript string value, and returns a reference to the new value.

func (*Context) NewUndefinedValue

func (ctx *Context) NewUndefinedValue() *Value

NewUndefinedValue creates a new JavaScript value of the undefined type, and returns a reference to the new value.

func (*Context) NewValue

func (ctx *Context) NewValue(value interface{}) *Value

NewValue creates a new JavaScript value representing the Go value. This functions can successfully convert all integers, unsigned integers, floats, boolean, and string values into JavaScript values. Some more complicated types can be wrapped. First, this function will wrap a Go function or closure into a JavaScript value that can be called from within the JavaScript context. Second, this function will wrap a structure or a pointer to a structure into a JavaScript value that will have the same properties and methods. If wrapping a pointer to a structure, updates to the fields in JavaScript will be visible in Go.

func (*Context) ProtectValue

func (ctx *Context) ProtectValue(ref *Value)

ProtectValue prevents a value from being garbage collected. In most cases, calling ProtectValue is unnecessary. However, if you want to store the Value for later use, then it must be protected. Calls to ProtectValue should be matched to calls to UnProtectValue when the Value is no longer needed.

func (*Context) SetProperty

func (ctx *Context) SetProperty(obj *Object, name string, rhs *Value, attributes uint8) (err *Value)

func (*Context) SetPropertyAtIndex

func (ctx *Context) SetPropertyAtIndex(obj *Object, index uint16, rhs *Value) (err *Value)

func (*Context) SetPrototype

func (ctx *Context) SetPrototype(obj *Object, rhs *Value)

func (*Context) ToBoolean

func (ctx *Context) ToBoolean(ref *Value) bool

ToBoolean returns the result of converting a JavaScript value to a boolean.

func (*Context) ToNumber

func (ctx *Context) ToNumber(ref *Value) (num float64, err *Value)

ToNumber returns the result of converting a JavaScript value to a number. If the conversion succeeds, the value is returned in num. If the conversion fails, the error raised by JavaScript is returned in err.

func (*Context) ToNumberOrDie

func (ctx *Context) ToNumberOrDie(ref *Value) float64

ToNumberOrDie returns the result of converting a JavaScript value to a number. If the conversion succeeds, the value is returned. If the conversion fails, the function panics with error raised by JavaScript.

func (*Context) ToObject

func (ctx *Context) ToObject(ref *Value) (obj *Object, err *Value)

ToObject returns the result of converting a JavaScript value to an object. If the conversion succeeds, the value is returned in num. If the conversion fails, the error raised by JavaScript is returned in err.

func (*Context) ToObjectOrDie

func (ctx *Context) ToObjectOrDie(ref *Value) *Object

ToObjectOrDie returns the result of converting a JavaScript value to an object. If the conversion succeeds, the value is returned. If the conversion fails, the function panics with error raised by JavaScript.

func (*Context) ToString

func (ctx *Context) ToString(ref *Value) (str string, err *Value)

ToString returns the result of converting a JavaScript value to a string. If the conversion succeeds, the value is returned in num. If the conversion fails, the error raised by JavaScript is returned in err.

func (*Context) ToStringOrDie

func (ctx *Context) ToStringOrDie(ref *Value) string

ToStringOrDie returns the result of converting a JavaScript value to a string. If the conversion succeeds, the value is returned. If the conversion fails, the function panics with error raised by JavaScript.

func (*Context) UnProtectValue

func (ctx *Context) UnProtectValue(ref *Value)

UnProtectValue undoes the protection from garbage collection. All calls should be matched with a preceeding call to ProtectValue.

type ContextGroup

type ContextGroup struct {
	// contains filtered or unexported fields
}

A ContextGroup associates JavaScript Contexts with one another. Objects may be shared between Contexts that belong to the same group.

type Error

type Error struct {
	Name    string
	Message string
	Context *Context
	Value   *Value
}

A Error wrap error information from a failed attempt to execute JavaScript code.

func (*Error) Error

func (e *Error) Error() string

type GlobalContext

type GlobalContext struct {
	Context
}

A GlobalContext is a global Context. A GlobalContext is a Context.

func NewGlobalContext

func NewGlobalContext() *GlobalContext

NewGlobalContext creates a new global JavaScript execution context. When the GlobalContext is no longer required, users should call Release.

func (*GlobalContext) Release

func (ctx *GlobalContext) Release()

Release realeases a GlobalContext.

func (*GlobalContext) Retain

func (ctx *GlobalContext) Retain()

Retain retains a GlobalContext. Every call to Retain should be matched with a following call to Release.

func (*GlobalContext) ToContext

func (ctx *GlobalContext) ToContext() *Context

ToContext provides a conversion to *Context. Since every GlobalContext is a Context, this function does no work. It serves simply to minimize the mismatch between Go's lack of support for inheritence.

type GoFunctionCallback

type GoFunctionCallback func(ctx *Context, obj *Object, thisObject *Object, arguments []*Value) (ret *Value)

A GoFunctionCallback is a function or closure that can be used to create a generic JavaScript function. See NewFunctionWithCallback.

type Kind

type Kind int

A Kind describes the type of a JavaScript value. It is the same as type of a JavaScript value, but renamed to match the naming convention of the reflect package in Go.

func (Kind) String

func (k Kind) String() string

String return a string describing the kind.

type Object

type Object struct {
	Value
}

An Object contains the state associated with a JavaScript object. There are very few member functions for this type. Most operations require an execution context (see the type Context).

An Object is a Value. However, in Go, a value with type *Object can not be used in place of a value with type *Value. To bridge this gap between the C API and Go, the member function ToValue is provided.

func (*Object) GetPrivate

func (obj *Object) GetPrivate() unsafe.Pointer

GetPrivate retrieves an unsafe pointer that has been stored with the JavaScript object.

func (*Object) SetPrivate

func (obj *Object) SetPrivate(data unsafe.Pointer) bool

SetPrivate stores an unsafe pointer with the JavaScript object. Note that the Go to JavaScript binding uses this field to associate JavaScript objects with native data in Go, and so users of the library should refrain from using this method with objects created to reflect native Go values.

func (*Object) ToValue

func (obj *Object) ToValue() *Value

ToValue casts the *Object to a *Value. Since in JavaScript every Object is a Value, this methods helps bridge the incompatibility between the C API and the Go API, where inheritence is not directly expressible.

type PropertyNameArray

type PropertyNameArray struct {
	// contains filtered or unexported fields
}

func (*PropertyNameArray) Count

func (ref *PropertyNameArray) Count() uint16

func (*PropertyNameArray) NameAtIndex

func (ref *PropertyNameArray) NameAtIndex(index uint16) string

func (*PropertyNameArray) Release

func (ref *PropertyNameArray) Release()

func (*PropertyNameArray) Retain

func (ref *PropertyNameArray) Retain()

type String

type String struct {
	// contains filtered or unexported fields
}

A String is a UTF-16 character buffer and is the native string representation in JavaScriptCore. Most users should not need to use this package, as the other functions within the library handle the necessary conversions between Go strings and JavaScriptCore strings.

func NewString

func NewString(value string) *String

New creates a new string representation native to JavaScriptCore. The newly created object has a reference count of one. The caller should make a call to the member function Release when the string is no longer required to free the allocated memory.

Example
// Allocate a new JavaScriptCore string.
str := NewString("a string")
// Ensure that the memory is released when the function returns.
defer str.Release()

fmt.Println(str)
Output:

a string

func (*String) Equal

func (ref *String) Equal(rhs *String) bool

Equal returns true if the two strings match.

func (*String) EqualToString

func (ref *String) EqualToString(rhs string) bool

Equal returns true if the two strings match, after converting the native Go string to UTF-16.

Example
str := NewString("a string")
defer str.Release()

if str.EqualToString("a different string") {
	fmt.Println("The two strings are equal.")
} else {
	fmt.Println("The two strings are not equal.")
}
Output:

The two strings are not equal.

func (*String) Length

func (ref *String) Length() uint32

Length returns the number of Unicode characters in the string

func (*String) Release

func (ref *String) Release()

Release decrements the internal reference count of the JavaScriptCore string object, and frees the memory when the count reaches zero. See the member function Retain.

func (*String) Retain

func (ref *String) Retain()

Retain increments the internal reference count of the JavaScriptCore string object. To avoid a memory leak, all calls to retain should be followed by a matching call to the member function Release.

func (*String) String

func (ref *String) String() string

String returns a native Go string in UTF-8 that matches the internal UTF-16 representation.

type Value

type Value struct {
	// contains filtered or unexported fields
}

An Value contains the state associated with a JavaScript value. Because all operations on a value occur within a Context, the functions for manipulating variables of type Value are all methods of Context objects.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL