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 ¶
- Constants
- type Context
- func (ctx *Context) CallAsConstructor(obj *Object, parameters []*Value) (val *Object, err *Value)
- func (ctx *Context) CallAsFunction(obj *Object, thisObject *Object, parameters []*Value) (val *Value, err *Value)
- func (ctx *Context) CheckScriptSyntax(script string, source_url string, startingLineNumber int) *Value
- func (ctx *Context) CopyPropertyNames(obj *Object) *PropertyNameArray
- func (ctx *Context) DeleteProperty(obj *Object, name string) (bool, *Value)
- func (ctx *Context) EvaluateScript(script string, thisObject *Object, source_url string, startingLineNumber int) (value *Value, error *Value)
- func (ctx *Context) GarbageCollect()
- func (ctx *Context) GetProperty(obj *Object, name string) (val *Value, err *Value)
- func (ctx *Context) GetPropertyAtIndex(obj *Object, index uint16) (val *Value, err *Value)
- func (ctx *Context) GetPrototype(obj *Object) *Value
- func (ctx *Context) GlobalObject() *Object
- func (ctx *Context) HasProperty(obj *Object, name string) bool
- func (ctx *Context) IsBoolean(v *Value) bool
- func (ctx *Context) IsConstructor(obj *Object) bool
- func (ctx *Context) IsEqual(a *Value, b *Value) (eq bool, err *Value)
- func (ctx *Context) IsFunction(obj *Object) bool
- func (ctx *Context) IsNull(v *Value) bool
- func (ctx *Context) IsNumber(v *Value) bool
- func (ctx *Context) IsObject(v *Value) bool
- func (ctx *Context) IsStrictEqual(a *Value, b *Value) bool
- func (ctx *Context) IsString(v *Value) bool
- func (ctx *Context) IsUndefined(v *Value) bool
- func (ctx *Context) Kind(v *Value) Kind
- func (ctx *Context) NewArray(items []*Value) (arr *Object, err *Value)
- func (ctx *Context) NewBooleanValue(value bool) *Value
- func (ctx *Context) NewDate() (date *Object, err *Value)
- func (ctx *Context) NewDateWithMilliseconds(milliseconds float64) (date *Object, err *Value)
- func (ctx *Context) NewDateWithString(date string) (obj *Object, err *Value)
- func (ctx *Context) NewError(message interface{}) (obj *Object, err *Value)
- func (ctx *Context) NewErrorFromString(message string) (obj *Object, err *Value)
- func (ctx *Context) NewFunction(name string, parameters []string, body string, source_url string, ...) (fn *Object, err *Value)
- func (ctx *Context) NewFunctionWithCallback(callback GoFunctionCallback) *Object
- func (ctx *Context) NewFunctionWithNative(fn interface{}) *Object
- func (ctx *Context) NewNativeObject(obj interface{}) *Object
- func (ctx *Context) NewNullValue() *Value
- func (ctx *Context) NewNumberValue(value float64) *Value
- func (ctx *Context) NewObject() *Object
- func (ctx *Context) NewRegExp(regex string) (re *Object, err *Value)
- func (ctx *Context) NewRegExpFromValues(parameters []*Value) (re *Object, err *Value)
- func (ctx *Context) NewString(value string) *Value
- func (ctx *Context) NewUndefinedValue() *Value
- func (ctx *Context) NewValue(value interface{}) *Value
- func (ctx *Context) ProtectValue(ref *Value)
- func (ctx *Context) SetProperty(obj *Object, name string, rhs *Value, attributes uint8) (err *Value)
- func (ctx *Context) SetPropertyAtIndex(obj *Object, index uint16, rhs *Value) (err *Value)
- func (ctx *Context) SetPrototype(obj *Object, rhs *Value)
- func (ctx *Context) ToBoolean(ref *Value) bool
- func (ctx *Context) ToNumber(ref *Value) (num float64, err *Value)
- func (ctx *Context) ToNumberOrDie(ref *Value) float64
- func (ctx *Context) ToObject(ref *Value) (obj *Object, err *Value)
- func (ctx *Context) ToObjectOrDie(ref *Value) *Object
- func (ctx *Context) ToString(ref *Value) (str string, err *Value)
- func (ctx *Context) ToStringOrDie(ref *Value) string
- func (ctx *Context) UnProtectValue(ref *Value)
- type ContextGroup
- type Error
- type GlobalContext
- type GoFunctionCallback
- type Kind
- type Object
- type PropertyNameArray
- type String
- type Value
Examples ¶
Constants ¶
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 (*Context) CallAsFunction ¶
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 (*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 (*Context) GetPropertyAtIndex ¶
func (*Context) GetPrototype ¶
func (*Context) GlobalObject ¶
GlobalObject returns the global object associated with an JavaScript execution context.
func (*Context) IsConstructor ¶
func (*Context) IsFunction ¶
func (*Context) IsUndefined ¶
IsUndefined returns true if the value has type undefined.
func (*Context) NewBooleanValue ¶
NewBooleanValue creates a new JavaScript boolean value, and returns a reference to the new value.
func (*Context) NewDateWithMilliseconds ¶
func (*Context) NewDateWithString ¶
func (*Context) NewErrorFromString ¶
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 ¶
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 ¶
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 ¶
NewNullValue creates a new JavaScript value of the null type, and returns a reference to the new value.
func (*Context) NewNumberValue ¶
NewNumberValue creates a new JavaScript number value, and returns a reference to the new value.
func (*Context) NewRegExpFromValues ¶
func (*Context) NewString ¶
NewString creates a new JavaScript string value, and returns a reference to the new value.
func (*Context) NewUndefinedValue ¶
NewUndefinedValue creates a new JavaScript value of the undefined type, and returns a reference to the new value.
func (*Context) NewValue ¶
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 ¶
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 (*Context) SetPropertyAtIndex ¶
func (*Context) SetPrototype ¶
func (*Context) ToBoolean ¶
ToBoolean returns the result of converting a JavaScript value to a boolean.
func (*Context) ToNumber ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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.
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 ¶
GetPrivate retrieves an unsafe pointer that has been stored with the JavaScript object.
func (*Object) SetPrivate ¶
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.
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 ¶
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) EqualToString ¶
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) 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.