Documentation
¶
Overview ¶
Package v8go provides an API to execute JavaScript.
Index ¶
- Variables
- func JSONStringify(ctx *Context, val Valuer) (string, error)
- func SetFlags(flags ...string)
- func Version() string
- type CPUProfile
- type CPUProfileNode
- func (c *CPUProfileNode) GetBailoutReason() string
- func (c *CPUProfileNode) GetChild(index int) *CPUProfileNode
- func (c *CPUProfileNode) GetChildrenCount() int
- func (c *CPUProfileNode) GetColumnNumber() int
- func (c *CPUProfileNode) GetFunctionName() string
- func (c *CPUProfileNode) GetHitCount() int
- func (c *CPUProfileNode) GetLineNumber() int
- func (c *CPUProfileNode) GetNodeId() int
- func (c *CPUProfileNode) GetParent() *CPUProfileNode
- func (c *CPUProfileNode) GetScriptId() int
- func (c *CPUProfileNode) GetScriptResourceName() string
- type CPUProfiler
- type CompileMode
- type CompileOptions
- type CompilerCachedData
- type ConsoleAPIMessage
- type ConsoleAPIMessageHandler
- type Context
- type ContextOption
- type Exception
- func NewError(iso *Isolate, msg string) *Exception
- func NewRangeError(iso *Isolate, msg string) *Exception
- func NewReferenceError(iso *Isolate, msg string) *Exception
- func NewSyntaxError(iso *Isolate, msg string) *Exception
- func NewTypeError(iso *Isolate, msg string) *Exception
- func NewWasmCompileError(iso *Isolate, msg string) *Exception
- func NewWasmLinkError(iso *Isolate, msg string) *Exception
- func NewWasmRuntimeError(iso *Isolate, msg string) *Exception
- type Function
- type FunctionCallback
- type FunctionCallbackInfo
- type FunctionCallbackWithError
- type FunctionTemplate
- func (tmpl *FunctionTemplate) GetFunction(ctx *Context) *Function
- func (tmpl *FunctionTemplate) Inherit(base *FunctionTemplate)
- func (tmpl *FunctionTemplate) InstanceTemplate() *ObjectTemplate
- func (tmpl *FunctionTemplate) PrototypeTemplate() *ObjectTemplate
- func (t FunctionTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error
- func (t FunctionTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error
- type HeapStatistics
- type Inspector
- type InspectorClient
- type Isolate
- func (i *Isolate) Close()deprecated
- func (i *Isolate) CompileUnboundScript(source, origin string, opts CompileOptions) (*UnboundScript, error)
- func (i *Isolate) Dispose()
- func (i *Isolate) GetHeapStatistics() HeapStatistics
- func (i *Isolate) IsExecutionTerminating() bool
- func (i *Isolate) LowMemoryNotification()
- func (i *Isolate) SetPromiseRejectedCallback(cb PromiseRejectedCallback)
- func (i *Isolate) TerminateExecution()
- func (i *Isolate) ThrowException(value *Value) *Value
- func (i *Isolate) WriteHeapSnapshot(w io.Writer) error
- type IsolateOption
- type JSError
- type Message
- type MessageErrorLevel
- type Object
- func (o *Object) Delete(key string) bool
- func (o *Object) DeleteIdx(idx uint32) bool
- func (o *Object) DeleteSymbol(key *Symbol) bool
- func (o *Object) Get(key string) (*Value, error)
- func (o *Object) GetIdx(idx uint32) (*Value, error)
- func (o *Object) GetInternalField(idx uint32) *Value
- func (o *Object) GetSymbol(key *Symbol) (*Value, error)
- func (o *Object) Has(key string) bool
- func (o *Object) HasIdx(idx uint32) bool
- func (o *Object) HasSymbol(key *Symbol) bool
- func (o *Object) InternalFieldCount() uint32
- func (o *Object) MethodCall(methodName string, args ...Valuer) (*Value, error)
- func (o *Object) Set(key string, val interface{}) error
- func (o *Object) SetIdx(idx uint32, val interface{}) error
- func (o *Object) SetInternalField(idx uint32, val interface{}) error
- func (o *Object) SetSymbol(key *Symbol, val interface{}) error
- type ObjectTemplate
- func (o *ObjectTemplate) InternalFieldCount() uint32
- func (o *ObjectTemplate) MarkAsUndetectable()
- func (o *ObjectTemplate) NewInstance(ctx *Context) (*Object, error)
- func (t ObjectTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error
- func (o *ObjectTemplate) SetAccessorProperty(key string, get *FunctionTemplate, set *FunctionTemplate, ...)
- func (o *ObjectTemplate) SetCallAsFunctionHandler(callback FunctionCallbackWithError)
- func (o *ObjectTemplate) SetInternalFieldCount(fieldCount uint32)
- func (t ObjectTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error
- type Promise
- func (p *Promise) Catch(cb FunctionCallback) *Promise
- func (p *Promise) CatchWithError(cb FunctionCallbackWithError) *Promise
- func (p *Promise) Result() *Value
- func (p *Promise) State() PromiseState
- func (p *Promise) Then(cbs ...FunctionCallback) *Promise
- func (p *Promise) ThenWithError(cbs ...FunctionCallbackWithError) *Promise
- type PromiseRejectEvent
- type PromiseRejectMessage
- type PromiseRejectedCallback
- type PromiseResolver
- type PromiseState
- type PropertyAttribute
- type StackFrame
- type Symbol
- func SymbolAsyncIterator(iso *Isolate) *Symbol
- func SymbolHasInstance(iso *Isolate) *Symbol
- func SymbolIsConcatSpreadable(iso *Isolate) *Symbol
- func SymbolIterator(iso *Isolate) *Symbol
- func SymbolMatch(iso *Isolate) *Symbol
- func SymbolReplace(iso *Isolate) *Symbol
- func SymbolSearch(iso *Isolate) *Symbol
- func SymbolSplit(iso *Isolate) *Symbol
- func SymbolToPrimitive(iso *Isolate) *Symbol
- func SymbolToStringTag(iso *Isolate) *Symbol
- func SymbolUnscopables(iso *Isolate) *Symbol
- type UnboundScript
- type Value
- func (v *Value) ArrayIndex() (idx uint32, ok bool)
- func (v *Value) AsException() (*Exception, error)
- func (v *Value) AsFunction() (*Function, error)
- func (v *Value) AsObject() (*Object, error)
- func (v *Value) AsPromise() (*Promise, error)
- func (v *Value) AsSymbol() (*Symbol, error)
- func (v *Value) BigInt() *big.Int
- func (v *Value) Boolean() bool
- func (v *Value) DetailString() string
- func (v *Value) External() (any, bool)
- func (v *Value) Format(s fmt.State, verb rune)
- func (v *Value) Int32() int32
- func (v *Value) Integer() int64
- func (v *Value) IsArgumentsObject() bool
- func (v *Value) IsArray() bool
- func (v *Value) IsArrayBuffer() bool
- func (v *Value) IsArrayBufferView() bool
- func (v *Value) IsAsyncFunction() bool
- func (v *Value) IsBigInt() bool
- func (v *Value) IsBigInt64Array() bool
- func (v *Value) IsBigIntObject() bool
- func (v *Value) IsBigUint64Array() bool
- func (v *Value) IsBoolean() bool
- func (v *Value) IsDataView() bool
- func (v *Value) IsDate() bool
- func (v *Value) IsExternal() bool
- func (v *Value) IsFalse() bool
- func (v *Value) IsFloat32Array() bool
- func (v *Value) IsFloat64Array() bool
- func (v *Value) IsFunction() bool
- func (v *Value) IsGeneratorFunction() bool
- func (v *Value) IsGeneratorObject() bool
- func (v *Value) IsInt8Array() bool
- func (v *Value) IsInt16Array() bool
- func (v *Value) IsInt32() bool
- func (v *Value) IsInt32Array() bool
- func (v *Value) IsMap() bool
- func (v *Value) IsMapIterator() bool
- func (v *Value) IsModuleNamespaceObject() bool
- func (v *Value) IsName() bool
- func (v *Value) IsNativeError() bool
- func (v *Value) IsNull() bool
- func (v *Value) IsNullOrUndefined() bool
- func (v *Value) IsNumber() bool
- func (v *Value) IsNumberObject() bool
- func (v *Value) IsObject() bool
- func (v *Value) IsPromise() bool
- func (v *Value) IsProxy() bool
- func (v *Value) IsRegExp() bool
- func (v *Value) IsSet() bool
- func (v *Value) IsSetIterator() bool
- func (v *Value) IsSharedArrayBuffer() bool
- func (v *Value) IsString() bool
- func (v *Value) IsStringObject() bool
- func (v *Value) IsSymbol() bool
- func (v *Value) IsSymbolObject() bool
- func (v *Value) IsTrue() bool
- func (v *Value) IsTypedArray() bool
- func (v *Value) IsUint8Array() bool
- func (v *Value) IsUint8ClampedArray() bool
- func (v *Value) IsUint16Array() bool
- func (v *Value) IsUint32() bool
- func (v *Value) IsUint32Array() bool
- func (v *Value) IsUndefined() bool
- func (v *Value) IsWasmModuleObject() bool
- func (v *Value) IsWeakMap() bool
- func (v *Value) IsWeakSet() bool
- func (v *Value) MarshalJSON() ([]byte, error)
- func (v *Value) Number() float64
- func (v *Value) Object() *Object
- func (v *Value) Release()
- func (v *Value) SameValue(other *Value) bool
- func (v *Value) SharedArrayBufferGetContents() ([]byte, func(), error)
- func (v *Value) StrictEquals(other *Value) bool
- func (v *Value) String() string
- func (v *Value) TypeOf() string
- func (v *Value) Uint32() uint32
- type ValueError
- type Valuer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( CompileModeDefault = CompileMode(C.ScriptCompilerNoCompileOptions) CompileModeEager = CompileMode(C.ScriptCompilerEagerCompile) )
var ErrHeapLimitReached = errors.New("heap limit reached")
ErrHeapLimitReached is matched by errors.Is for errors from executing JavaScript that was terminated because the isolate's heap limit was reached. The process isn't killed; the isolate can be used again.
Functions ¶
func JSONStringify ¶
JSONStringify tries to stringify the JSON-serializable object value and returns it as string.
Example ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
ctx := v8.NewContext()
defer ctx.Isolate().Dispose()
defer ctx.Close()
val, _ := v8.JSONParse(ctx, `{
"a": 1,
"b": "foo"
}`)
jsonStr, _ := v8.JSONStringify(ctx, val)
fmt.Println(jsonStr)
}
Output: {"a":1,"b":"foo"}
func SetFlags ¶
func SetFlags(flags ...string)
SetFlags sets flags for V8. For possible flags: https://github.com/v8/v8/blob/master/src/flags/flag-definitions.h Flags are expected to be prefixed with `--`, for example: `--harmony`. Flags can be reverted using the `--no` prefix equivalent, for example: `--use_strict` vs `--nouse_strict`. Flags will affect all Isolates created, even after creation.
Types ¶
type CPUProfile ¶
type CPUProfile struct {
// contains filtered or unexported fields
}
func (*CPUProfile) Delete ¶
func (c *CPUProfile) Delete()
Deletes the profile and removes it from CpuProfiler's list. All pointers to nodes previously returned become invalid.
func (*CPUProfile) GetDuration ¶
func (c *CPUProfile) GetDuration() time.Duration
Returns the duration of the profile.
func (*CPUProfile) GetTopDownRoot ¶
func (c *CPUProfile) GetTopDownRoot() *CPUProfileNode
Returns the root node of the top down call tree.
type CPUProfileNode ¶
type CPUProfileNode struct {
// contains filtered or unexported fields
}
func (*CPUProfileNode) GetBailoutReason ¶
func (c *CPUProfileNode) GetBailoutReason() string
Returns the bailout reason for the function if the optimization was disabled for it.
func (*CPUProfileNode) GetChild ¶
func (c *CPUProfileNode) GetChild(index int) *CPUProfileNode
Retrieves a child node by index.
func (*CPUProfileNode) GetChildrenCount ¶
func (c *CPUProfileNode) GetChildrenCount() int
func (*CPUProfileNode) GetColumnNumber ¶
func (c *CPUProfileNode) GetColumnNumber() int
Returns number of the column where the function originates.
func (*CPUProfileNode) GetFunctionName ¶
func (c *CPUProfileNode) GetFunctionName() string
Returns function name (empty string for anonymous functions.)
func (*CPUProfileNode) GetHitCount ¶
func (c *CPUProfileNode) GetHitCount() int
Returns count of samples where the function was currently executing.
func (*CPUProfileNode) GetLineNumber ¶
func (c *CPUProfileNode) GetLineNumber() int
Returns number of the line where the function originates.
func (*CPUProfileNode) GetParent ¶
func (c *CPUProfileNode) GetParent() *CPUProfileNode
Retrieves the ancestor node, or nil if the root.
func (*CPUProfileNode) GetScriptId ¶
func (c *CPUProfileNode) GetScriptId() int
Returns id for script from where the function originates.
func (*CPUProfileNode) GetScriptResourceName ¶
func (c *CPUProfileNode) GetScriptResourceName() string
Returns resource name for script from where the function originates.
type CPUProfiler ¶
type CPUProfiler struct {
// contains filtered or unexported fields
}
func NewCPUProfiler ¶
func NewCPUProfiler(iso *Isolate) *CPUProfiler
CPUProfiler is used to control CPU profiling.
func (*CPUProfiler) Do ¶ added in v0.38.0
func (c *CPUProfiler) Do(title string, fn func()) *CPUProfile
Do collects a CPU profile of fn, and returns it.
The profile only contains samples from JavaScript executing on the calling goroutine, so fn must not execute JavaScript on other goroutines. To ensure this, Do locks the goroutine to its OS thread while running fn. If fn panics, or calls runtime.Goexit, the profile is discarded.
Do is the preferred way of profiling, since it guarantees the thread requirements of StartProfiling.
func (*CPUProfiler) StartProfiling ¶
func (c *CPUProfiler) StartProfiling(title string)
StartProfiling starts collecting a CPU profile. Title may be an empty string. Several profiles may be collected at once. Attempts to start collecting several profiles with the same title are silently ignored.
V8 only samples the OS thread that called StartProfiling. Until StopProfiling, JavaScript executing on any other thread is silently missing from the profile. Since the Go scheduler may move goroutines between OS threads, the caller must call runtime.LockOSThread before StartProfiling, and execute JavaScript on the same goroutine. Use Do to have this done automatically.
func (*CPUProfiler) StopProfiling ¶
func (c *CPUProfiler) StopProfiling(title string) *CPUProfile
Stops collecting CPU profile with a given title and returns it. If the title given is empty, finishes the last profile started.
type CompileMode ¶
type CompileOptions ¶
type CompileOptions struct {
CachedData *CompilerCachedData
Mode CompileMode
}
type CompilerCachedData ¶
type ConsoleAPIMessage ¶ added in v0.29.0
type ConsoleAPIMessage struct {
ErrorLevel MessageErrorLevel
Message string
Url string
LineNumber uint
ColumnNumber uint
// contains filtered or unexported fields
}
ConsoleAPIMessage contains the information from v8 from console function calls.
The fields correspond to the arguments for the C++ function v8_inspector::InspectorClient::consoleAPIMessage
Note: Stack traces are not supported.
See also: https://v8.github.io/api/head/classv8__inspector_1_1V8InspectorClient.html
type ConsoleAPIMessageHandler ¶ added in v0.29.0
type ConsoleAPIMessageHandler interface {
ConsoleAPIMessage(message ConsoleAPIMessage)
}
A ConsoleAPIMessageHandler will receive JavaScript `console` API calls.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is a global root execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8.
Example ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
ctx := v8.NewContext()
defer ctx.Isolate().Dispose()
defer ctx.Close()
ctx.RunScript("const add = (a, b) => a + b", "math.js")
ctx.RunScript("const result = add(3, 4)", "main.js")
val, _ := ctx.RunScript("result", "value.js")
fmt.Println(val)
}
Output: 7
Example (GlobalTemplate) ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
obj := v8.NewObjectTemplate(iso)
obj.Set("version", "v1.0.0")
ctx := v8.NewContext(iso, obj)
defer ctx.Close()
val, _ := ctx.RunScript("version", "main.js")
fmt.Println(val)
}
Output: v1.0.0
Example (Isolate) ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
ctx1 := v8.NewContext(iso)
defer ctx1.Close()
ctx1.RunScript("const foo = 'bar'", "context_one.js")
val, _ := ctx1.RunScript("foo", "foo.js")
fmt.Println(val)
ctx2 := v8.NewContext(iso)
defer ctx2.Close()
_, err := ctx2.RunScript("foo", "context_two.js")
fmt.Println(err)
}
Output: bar ReferenceError: foo is not defined
func NewContext ¶
func NewContext(opt ...ContextOption) *Context
NewContext creates a new JavaScript context; if no Isolate is passed as a ContextOption than a new Isolate will be created.
func (*Context) Close ¶
func (c *Context) Close()
Close will dispose the context and free the memory. Access to any values associated with the context after calling Close may panic.
func (*Context) Global ¶
Global returns the global proxy object. Global proxy object is a thin wrapper whose prototype points to actual context's global object with the properties like Object, etc. This is done that way for security reasons. Please note that changes to global proxy object prototype most probably would break the VM — V8 expects only global object as a prototype of global proxy object.
func (*Context) PerformMicrotaskCheckpoint ¶
func (c *Context) PerformMicrotaskCheckpoint()
PerformMicrotaskCheckpoint runs the default MicrotaskQueue until empty. This is used to make progress on Promises.
func (*Context) RetainedValueCount ¶
type ContextOption ¶
type ContextOption interface {
// contains filtered or unexported methods
}
ContextOption sets options such as Isolate and Global Template to the NewContext
type Exception ¶
type Exception struct {
*Value
}
An Exception is a JavaScript exception.
func NewRangeError ¶
NewRangeError creates a RangeError.
func NewReferenceError ¶
NewReferenceError creates a ReferenceError.
func NewSyntaxError ¶
NewSyntaxError creates a SyntaxError.
func NewTypeError ¶
NewTypeError creates a TypeError.
func NewWasmCompileError ¶
NewWasmCompileError creates a WasmCompileError.
func NewWasmLinkError ¶
NewWasmLinkError creates a WasmLinkError.
func NewWasmRuntimeError ¶
NewWasmRuntimeError creates a WasmRuntimeError.
type Function ¶
type Function struct {
*Value
}
Function is a JavaScript function.
func (*Function) NewInstance ¶
Invoke a constructor function to create an object instance.
func (*Function) SourceMapUrl ¶
Return the source map url for a function.
type FunctionCallback ¶
type FunctionCallback func(info *FunctionCallbackInfo) *Value
FunctionCallback is a callback that is executed in Go when a function is executed in JS.
type FunctionCallbackInfo ¶
type FunctionCallbackInfo struct {
// contains filtered or unexported fields
}
FunctionCallbackInfo is the argument that is passed to a FunctionCallback.
func (*FunctionCallbackInfo) Args ¶
func (i *FunctionCallbackInfo) Args() []*Value
Args returns a slice of the value arguments that are passed to the JS function.
func (*FunctionCallbackInfo) Context ¶
func (i *FunctionCallbackInfo) Context() *Context
Context is the current context that the callback is being executed in.
func (*FunctionCallbackInfo) Release ¶
func (i *FunctionCallbackInfo) Release()
func (*FunctionCallbackInfo) This ¶
func (i *FunctionCallbackInfo) This() *Object
This returns the receiver object "this".
type FunctionCallbackWithError ¶
type FunctionCallbackWithError func(info *FunctionCallbackInfo) (*Value, error)
FunctionCallbackWithError is a callback that is executed in Go when a function is executed in JS. If a ValueError is returned, its value will be thrown as an exception in V8, otherwise Error() is invoked, and the string is thrown.
type FunctionTemplate ¶
type FunctionTemplate struct {
// contains filtered or unexported fields
}
FunctionTemplate is used to create functions at runtime. There can only be one function created from a FunctionTemplate in a context. The lifetime of the created function is equal to the lifetime of the context.
A FunctionTemplate can be used to create "constructors", and add methods to the "class". FunctionTemplate.PrototypeTemplate can be used to add normal methods on the class, and FunctionTemplate.InstanceTemplate can be used to add fields automatically to new instances of a class.
V8 API Docs: https://v8.github.io/api/head/classv8_1_1FunctionTemplate.html
Example ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
global := v8.NewObjectTemplate(iso)
printfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
fmt.Printf("%+v\n", info.Args())
return nil
})
global.Set("print", printfn, v8.ReadOnly)
ctx := v8.NewContext(iso, global)
defer ctx.Close()
ctx.RunScript("print('foo', 'bar', 0, 1)", "")
}
Output: [foo bar 0 1]
Example (Fetch) ¶
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
global := v8.NewObjectTemplate(iso)
fetchfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
args := info.Args()
url := args[0].String()
resolver, _ := v8.NewPromiseResolver(info.Context())
go func() {
res, _ := http.Get(url)
body, _ := ioutil.ReadAll(res.Body)
val, _ := v8.NewValue(iso, string(body))
resolver.Resolve(val)
}()
return resolver.GetPromise().Value
})
global.Set("fetch", fetchfn, v8.ReadOnly)
ctx := v8.NewContext(iso, global)
defer ctx.Close()
val, _ := ctx.RunScript("fetch('https://rogchap.com/v8go')", "")
prom, _ := val.AsPromise()
// wait for the promise to resolve
for prom.State() == v8.Pending {
continue
}
fmt.Printf("%s\n", strings.Split(prom.Result().String(), "\n")[0])
}
Output: <!DOCTYPE html>
func NewFunctionTemplate ¶
func NewFunctionTemplate(iso *Isolate, callback FunctionCallback) *FunctionTemplate
NewFunctionTemplate creates a FunctionTemplate for a given callback. Prefer using NewFunctionTemplateWithError.
func NewFunctionTemplateWithError ¶
func NewFunctionTemplateWithError( iso *Isolate, callback FunctionCallbackWithError, ) *FunctionTemplate
NewFunctionTemplateWithError creates a FunctionTemplate for a given callback. If the callback returns an error, it will be thrown as a JS error.
func (*FunctionTemplate) GetFunction ¶
func (tmpl *FunctionTemplate) GetFunction(ctx *Context) *Function
GetFunction returns an instance of this function template bound to the given context.
func (*FunctionTemplate) Inherit ¶ added in v0.33.0
func (tmpl *FunctionTemplate) Inherit(base *FunctionTemplate)
func (*FunctionTemplate) InstanceTemplate ¶ added in v0.29.0
func (tmpl *FunctionTemplate) InstanceTemplate() *ObjectTemplate
InstanceTemplate gets the ObjectTemplate that is used for new object instances created when this function is used as a constructor.
You can add functions and values to new instance using ObjectTemplate.Set and ObjectTemplate.SetSymbol. Those values will become own properties on the instance, not the prototype.
Adding a function to an instance template corresponds to the following JavaScript:
class Example() {
constructor() {
this.foo = function() { /* creates a function on the instance */ }
}
}
func (*FunctionTemplate) PrototypeTemplate ¶ added in v0.29.0
func (tmpl *FunctionTemplate) PrototypeTemplate() *ObjectTemplate
PrototypeTemplate gets the ObjectTemplate that is used to create the prototype object associated with the function.
You can call ObjectTemplate.Set or ObjectTemplate.SetSymbol, passing a FunctionTemplate to add a "method" to the class.
Adding a function to a prototype template corresponds normal method on a JavaScript "class":
class Example {
foo() { /* this is a method on the prototype */ }
}
Or the old-school way
function Example() {}
Example.prototype.foo = function() { }
The function becomes an own property on the prototype, not the instance.
func (FunctionTemplate) Set ¶
func (t FunctionTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error
Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.
func (FunctionTemplate) SetSymbol ¶
func (t FunctionTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error
SetSymbol adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.
type HeapStatistics ¶
type HeapStatistics struct {
TotalHeapSize uint64
TotalHeapSizeExecutable uint64
TotalPhysicalSize uint64
TotalAvailableSize uint64
UsedHeapSize uint64
HeapSizeLimit uint64
MallocedMemory uint64
ExternalMemory uint64
PeakMallocedMemory uint64
NumberOfNativeContexts uint64
NumberOfDetachedContexts uint64
}
HeapStatistics represents V8 isolate heap statistics
type Inspector ¶ added in v0.29.0
type Inspector struct {
// contains filtered or unexported fields
}
An Inspector in v8 provides access to internals of the engine, such as console output
To receive console output, you need to first create an InspectorClient which will handle the interaction for a specific Context.
After a Context is created, you need to register it with the Inspector using Inspector.ContextCreated, and cleanup using Inspector.ContextDestroyed.
See also: https://v8.github.io/api/head/classv8__inspector_1_1V8Inspector.html
func NewInspector ¶ added in v0.29.0
func NewInspector(iso *Isolate, client *InspectorClient) *Inspector
NewInspector creates an Inspector for a specific Isolate iso communicating with the InspectorClient client.
Before disposing the iso, be sure to dispose the inspector using Inspector.Dispose
func (*Inspector) ContextCreated ¶ added in v0.29.0
ContextCreated tells the inspector that a new Context has been created. This must be called before the InspectorClient can be used.
func (*Inspector) ContextDestroyed ¶ added in v0.29.0
ContextDestroyed must be called before a Context is closed.
type InspectorClient ¶ added in v0.29.0
type InspectorClient struct {
// contains filtered or unexported fields
}
An InspectorClient is the bridge from the Inspector to your code.
func NewInspectorClient ¶ added in v0.29.0
func NewInspectorClient(handler ConsoleAPIMessageHandler) *InspectorClient
Create a new InspectorClient passing a handler that will receive the callbacks from v8.
func (*InspectorClient) Dispose ¶ added in v0.29.0
func (c *InspectorClient) Dispose()
Dispose frees up resources taken up by the InspectorClient. Be sure to call this after calling Inspector.Dispose
type Isolate ¶
type Isolate struct {
// contains filtered or unexported fields
}
Isolate is a JavaScript VM instance with its own heap and garbage collector. Most applications will create one isolate with many V8 contexts for execution.
func NewIsolate ¶
func NewIsolate(opts ...IsolateOption) *Isolate
NewIsolate creates a new V8 isolate with the provided options. Only one thread may access a given isolate at a time, but different threads may access different isolates simultaneously. When an isolate is no longer used its resources should be freed by calling iso.Dispose(). An *Isolate can be used as a v8go.ContextOption to create a new Context, rather than creating a new default Isolate.
func (*Isolate) CompileUnboundScript ¶
func (i *Isolate) CompileUnboundScript( source, origin string, opts CompileOptions, ) (*UnboundScript, error)
CompileUnboundScript will create an UnboundScript (i.e. context-indepdent) using the provided source JavaScript, origin (a.k.a. filename), and options. If options contain a non-null CachedData, compilation of the script will use that code cache. error will be of type `JSError` if not nil.
func (*Isolate) Dispose ¶
func (i *Isolate) Dispose()
Dispose will dispose the Isolate VM; subsequent calls will panic.
func (*Isolate) GetHeapStatistics ¶
func (i *Isolate) GetHeapStatistics() HeapStatistics
GetHeapStatistics returns heap statistics for an isolate.
func (*Isolate) IsExecutionTerminating ¶
IsExecutionTerminating returns whether V8 is currently terminating Javascript execution. If true, there are still JavaScript frames on the stack and the termination exception is still active.
func (*Isolate) LowMemoryNotification ¶ added in v0.36.0
func (i *Isolate) LowMemoryNotification()
LowMemoryNotification tells V8 that the system is running low on memory. V8 then performs a full garbage collection, and frees other memory it can, e.g. caches.
func (*Isolate) SetPromiseRejectedCallback ¶ added in v0.38.0
func (i *Isolate) SetPromiseRejectedCallback(cb PromiseRejectedCallback)
SetPromiseRejectedCallback sets the callback to be called for promise rejection events. This includes rejections that happen while V8 runs microtasks after a script has finished. A nil callback removes it. An Isolate has at most one callback, so this replaces any previous one.
The callback runs synchronously inside V8, and must not run JavaScript in the context of the promise.
The callback is not called for promises created in a closed Context, since their values can't be tracked. This can happen if a closed context's promise is still reachable from another context.
func (*Isolate) TerminateExecution ¶
func (i *Isolate) TerminateExecution()
TerminateExecution terminates forcefully the current thread of JavaScript execution in the given isolate.
func (*Isolate) ThrowException ¶
ThrowException schedules an exception to be thrown when returning to JavaScript. When an exception has been scheduled it is illegal to invoke any JavaScript operation; the caller must return immediately and only after the exception has been handled does it become legal to invoke JavaScript operations.
func (*Isolate) WriteHeapSnapshot ¶ added in v0.36.0
WriteHeapSnapshot takes a snapshot of the JavaScript heap and writes it to w, in the JSON format that Chrome DevTools can load (".heapsnapshot" files). Comparing snapshots taken at different times is useful for finding memory leaks. V8 performs a full garbage collection before taking the snapshot.
The isolate is locked while the snapshot is written. The returned error is the first error returned by w.
type IsolateOption ¶ added in v0.34.0
type IsolateOption func(*isolateConfig)
IsolateOption configures an Isolate on creation.
func WithExceptionMessages ¶ added in v0.36.0
func WithExceptionMessages() IsolateOption
WithExceptionMessages makes errors from JavaScript exceptions include details, such as the stack frames, returned by JSError.ExceptionMessage. This costs time and memory on every error, so it's off by default.
func WithResourceConstraints ¶ added in v0.34.0
func WithResourceConstraints(initialHeapSizeInBytes, maxHeapSizeInBytes uint64) IsolateOption
WithResourceConstraints sets memory constraints for the isolate.
When any isolate reaches its heap limit, v8go terminates the running script instead of letting V8 end the process. The returned error then matches ErrHeapLimitReached, and the isolate can be used again.
type JSError ¶
type JSError struct {
Message string
Location string
StackTrace string
// contains filtered or unexported fields
}
JSError is an error that is returned if there is are any JavaScript exceptions handled in the context. When used with the fmt verb `%+v`, will output the JavaScript stack trace, if available.
func (*JSError) ExceptionMessage ¶ added in v0.36.0
ExceptionMessage returns details about where the exception happened. It returns nil unless the isolate was created WithExceptionMessages, or if V8 reported no message, e.g. when execution was terminated.
type Message ¶ added in v0.36.0
type Message struct {
// Text is the message, e.g. "Uncaught ReferenceError: c is not defined".
Text string
// ScriptResourceName is the name of the script, e.g. the origin
// passed to RunScript.
ScriptResourceName string
// SourceLine is the line of source code where the exception happened.
SourceLine string
// LineNumber is 1-based, or 0 if unknown.
LineNumber int
// StartPosition and EndPosition are 0-based offsets into the script.
StartPosition, EndPosition int
// StartColumn and EndColumn are 0-based.
StartColumn, EndColumn int
// WASMFunctionIndex is the WebAssembly function, or -1.
WASMFunctionIndex int
// StackTrace is where the exception was thrown, innermost first.
StackTrace []StackFrame
}
Message describes a JavaScript exception, as reported by V8.
type MessageErrorLevel ¶ added in v0.29.0
type MessageErrorLevel uint8
Represents the level of console output from JavaScript. E.g., `console.log`, `console.error`, etc.
The values reflect the values of v8::Isolate::MessageErrorLevel
See also: https://v8.github.io/api/head/classv8_1_1Isolate.html
const ( ErrorLevelLog MessageErrorLevel = 1 << iota ErrorLevelDebug ErrorLevelInfo ErrorLevelError ErrorLevelWarning ErrorLevelAll = ErrorLevelLog | ErrorLevelDebug | ErrorLevelInfo | ErrorLevelError | ErrorLevelWarning )
func (MessageErrorLevel) String ¶ added in v0.29.0
func (lvl MessageErrorLevel) String() string
type Object ¶
type Object struct {
*Value
}
Object is a JavaScript object (ECMA-262, 4.3.3)
Example (Global) ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
ctx := v8.NewContext(iso)
defer ctx.Close()
global := ctx.Global()
console := v8.NewObjectTemplate(iso)
logfn := v8.NewFunctionTemplate(iso, func(info *v8.FunctionCallbackInfo) *v8.Value {
fmt.Println(info.Args()[0])
return nil
})
console.Set("log", logfn)
consoleObj, _ := console.NewInstance(ctx)
global.Set("console", consoleObj)
ctx.RunScript("console.log('foo')", "")
}
Output: foo
func (*Object) Delete ¶
Delete returns true if successful in deleting a named property on the object.
func (*Object) DeleteIdx ¶
DeleteIdx returns true if successful in deleting a value at a given index of the object.
func (*Object) DeleteSymbol ¶
DeleteSymbol returns true if successful in deleting a named property on the object.
func (*Object) GetInternalField ¶
GetInternalField gets the Value set by SetInternalField for the given index or the JS undefined value if the index hadn't been set. Panics if given an out of range index, or the field contains a Data other than a Value.
func (*Object) Has ¶
Has calls the abstract operation HasProperty(O, P) described in ECMA-262, 7.3.10. Returns true, if the object has the property, either own or on the prototype chain.
func (*Object) HasSymbol ¶
HasSymbol calls the abstract operation HasProperty(O, P) described in ECMA-262, 7.3.10. Returns true, if the object has the property, either own or on the prototype chain.
func (*Object) InternalFieldCount ¶
InternalFieldCount returns the number of internal fields this Object has.
func (*Object) MethodCall ¶
func (*Object) Set ¶
Set will set a property on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.
func (*Object) SetIdx ¶
Set will set a given index on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.
func (*Object) SetInternalField ¶
SetInternalField sets the value of an internal field for an ObjectTemplate instance. The object must be created from an ObjectTemplate, either from a call to ObjectTemplate.NewInstance, or as a new instance of a class, in which case the object template is the FunctionTemplate.InstanceTemplate of the constructor.
Before setting the internal field, it is necessary to call ObjectTemplate.SetInternalFieldCount indicating how many internal fields exist.
The function panics if the object is not created from an object template, or the index is outside the range of internal field count.
Example use cases:
- An object implementing a javascript iterator can store the current index being iterated.
- An object that exposes a native Go object to script code can store a reference. See also NewValue for this case.
func (*Object) SetSymbol ¶
SetSymbol will set a property on the Object to a given value. Supports all value types, eg: Object, Array, Date, Set, Map etc If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a *Value will be created and set as the value property.
type ObjectTemplate ¶
type ObjectTemplate struct {
// contains filtered or unexported fields
}
ObjectTemplate is used to create objects at runtime. Properties added to an ObjectTemplate are added to each object created from the ObjectTemplate.
func NewObjectTemplate ¶
func NewObjectTemplate(iso *Isolate) *ObjectTemplate
NewObjectTemplate creates a new ObjectTemplate. The *ObjectTemplate can be used as a v8go.ContextOption to create a global object in a Context.
func (*ObjectTemplate) InternalFieldCount ¶
func (o *ObjectTemplate) InternalFieldCount() uint32
InternalFieldCount returns the number of internal fields that instances of this template will have.
func (*ObjectTemplate) MarkAsUndetectable ¶ added in v0.34.0
func (o *ObjectTemplate) MarkAsUndetectable()
MarkAsUndetectable marks object instances of the template as undetectable. Undetectable objects behave like undefined, but you can access properties defined on undetectable objects.
Note: Undetectable objects MUST have a CallAsFunctionHandler, see ObjectTemplate.SetCallAsFunctionHandler
func (*ObjectTemplate) NewInstance ¶
func (o *ObjectTemplate) NewInstance(ctx *Context) (*Object, error)
NewInstance creates a new Object based on the template.
func (ObjectTemplate) Set ¶
func (t ObjectTemplate) Set(name string, val interface{}, attributes ...PropertyAttribute) error
Set adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.
func (*ObjectTemplate) SetAccessorProperty ¶ added in v0.33.0
func (o *ObjectTemplate) SetAccessorProperty( key string, get *FunctionTemplate, set *FunctionTemplate, attributes PropertyAttribute, )
SetAccessorProperty creates a named accessor property, i.e., a property that is implemented as a function call. Arguments get and set represents the getter and setter, and can both be nil.
Note: The ReadOnly should not be used with a readonly property. If set is nil, the property will be readonly, and passing None is a sensible default.
This corresponds to ObjectTemplate::SetAccessorProperty in the C++ API.
Example ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
tmpl := v8.NewObjectTemplate(iso)
tmpl.SetAccessorProperty(
"prop",
// Getter
v8.NewFunctionTemplateWithError(
iso,
func(*v8.FunctionCallbackInfo) (*v8.Value, error) {
return v8.NewValue(iso, "Value")
},
),
nil, // Setter
v8.None,
)
global := v8.NewObjectTemplate(iso)
global.Set("obj", tmpl)
ctx := v8.NewContext(iso, global)
defer ctx.Close()
value, _ := ctx.RunScript("obj.prop", "")
fmt.Printf("Property value: %s\n", value.String())
}
Output: Property value: Value
Example (Helpers) ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
// SetObjectTemplateAccessorProperty shows an example of a helper that client
// code could optionally introduce.
//
// ObjectTemplate.SetAccessorProperty requires FunctionTemplate instances as
// arguments, but you rarely need the actual function template outside the
// scope of setting an accessor property.
//
// If many accessor properties must be created, this example could reduce
// repetitive trivial code.
func SetObjectTemplateAccessorProperty(
iso *v8.Isolate,
templ *v8.ObjectTemplate,
key string,
get v8.FunctionCallbackWithError,
set v8.FunctionCallbackWithError,
attributes v8.PropertyAttribute,
) {
var (
v8get *v8.FunctionTemplate
v8set *v8.FunctionTemplate
)
if get != nil {
v8get = v8.NewFunctionTemplateWithError(iso, get)
}
if set != nil {
v8set = v8.NewFunctionTemplateWithError(iso, set)
}
templ.SetAccessorProperty(key, v8get, v8set, attributes)
}
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
tmpl := v8.NewObjectTemplate(iso)
current, _ := v8.NewValue(iso, "current")
SetObjectTemplateAccessorProperty(iso, tmpl,
"prop",
// Getter
func(*v8.FunctionCallbackInfo) (*v8.Value, error) {
return current, nil
},
// Setter
func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
current = info.Args()[0]
return nil, nil
},
v8.None,
)
global := v8.NewObjectTemplate(iso)
global.Set("obj", tmpl)
ctx := v8.NewContext(iso, global)
defer ctx.Close()
value, _ := ctx.RunScript("obj.prop", "")
fmt.Printf("Property value before set: %s\n", value.String())
value, _ = ctx.RunScript("obj.prop = 'new value'; obj.prop", "")
fmt.Printf("Property value after set: %s\n", value.String())
}
Output: Property value before set: current Property value after set: new value
func (*ObjectTemplate) SetCallAsFunctionHandler ¶ added in v0.34.0
func (o *ObjectTemplate) SetCallAsFunctionHandler(callback FunctionCallbackWithError)
SetCallAsFunctionHandler sets the callback to be used when calling instances created from this template. If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function.
func (*ObjectTemplate) SetInternalFieldCount ¶
func (o *ObjectTemplate) SetInternalFieldCount(fieldCount uint32)
SetInternalFieldCount sets the number of internal fields that instances of this template will have.
func (ObjectTemplate) SetSymbol ¶
func (t ObjectTemplate) SetSymbol(key *Symbol, val interface{}, attributes ...PropertyAttribute) error
SetSymbol adds a property to each instance created by this template. The property must be defined either as a primitive value, or a template. If the value passed is a Go supported primitive (string, int32, uint32, int64, uint64, float64, big.Int) then a value will be created and set as the value property.
type Promise ¶
type Promise struct {
*Object
}
Promise is the JavaScript promise object defined in ES6
func (*Promise) Catch ¶
func (p *Promise) Catch(cb FunctionCallback) *Promise
Catch invokes the given function if the promise is rejected. See Then for other details.
func (*Promise) CatchWithError ¶
func (p *Promise) CatchWithError(cb FunctionCallbackWithError) *Promise
func (*Promise) Result ¶
Result is the value result of the Promise. The Promise must NOT be in a Pending state, otherwise may panic. Call promise.State() to validate state before calling for the result.
func (*Promise) State ¶
func (p *Promise) State() PromiseState
State returns the current state of the Promise.
func (*Promise) Then ¶
func (p *Promise) Then(cbs ...FunctionCallback) *Promise
Then accepts 1 or 2 callbacks. The first is invoked when the promise has been fulfilled. The second is invoked when the promise has been rejected. The returned Promise resolves after the callback finishes execution.
V8 only invokes the callback when processing "microtasks". The default MicrotaskPolicy processes them when the call depth decreases to 0. Call (*Context).PerformMicrotaskCheckpoint to trigger it manually.
func (*Promise) ThenWithError ¶
func (p *Promise) ThenWithError(cbs ...FunctionCallbackWithError) *Promise
type PromiseRejectEvent ¶ added in v0.38.0
type PromiseRejectEvent uint8
PromiseRejectEvent is the kind of event passed to a PromiseRejectedCallback. The values mirror v8::PromiseRejectEvent.
See also: https://v8.github.io/api/head/namespacev8.html
const ( // PromiseRejectWithNoHandler is sent when a promise is rejected, and // it has no rejection handler. PromiseRejectWithNoHandler PromiseRejectEvent = 0 // PromiseHandlerAddedAfterReject is sent when a rejection handler is // added to a promise that has already been rejected. E.g., the // following sends a PromiseRejectWithNoHandler event, followed by a // PromiseHandlerAddedAfterReject event: // // Promise.reject("dummy").catch(e => {}) PromiseHandlerAddedAfterReject PromiseRejectEvent = 1 )
func (PromiseRejectEvent) String ¶ added in v0.38.0
func (e PromiseRejectEvent) String() string
type PromiseRejectMessage ¶ added in v0.38.0
type PromiseRejectMessage struct {
// Context is the context the promise was created in.
Context *Context
Promise *Promise
Event PromiseRejectEvent
// Value is the rejection value. It is nil for
// PromiseHandlerAddedAfterReject.
Value *Value
}
PromiseRejectMessage is passed to a PromiseRejectedCallback. The fields reflect v8::PromiseRejectMessage.
See also: https://v8.github.io/api/head/classv8_1_1PromiseRejectMessage.html
type PromiseRejectedCallback ¶ added in v0.38.0
type PromiseRejectedCallback func(PromiseRejectMessage)
PromiseRejectedCallback is called with promise rejection events. See Isolate.SetPromiseRejectedCallback.
type PromiseResolver ¶
type PromiseResolver struct {
*Object
// contains filtered or unexported fields
}
PromiseResolver is the resolver object for the promise. Most cases will create a new PromiseResolver and return the associated Promise from the resolver.
func NewPromiseResolver ¶
func NewPromiseResolver(ctx *Context) (*PromiseResolver, error)
NewPromiseResolver creates a new Promise resolver for the given context. The associated Promise will be in a Pending state.
func (*PromiseResolver) GetPromise ¶
func (r *PromiseResolver) GetPromise() *Promise
GetPromise returns the associated Promise object for this resolver. The Promise object is unique to the resolver and returns the same object on multiple calls.
func (*PromiseResolver) Reject ¶
func (r *PromiseResolver) Reject(err *Value) bool
Reject invokes the Promise reject state with the given value. The Promise state will transition from Pending to Rejected.
func (*PromiseResolver) Resolve ¶
func (r *PromiseResolver) Resolve(val Valuer) bool
Resolve invokes the Promise resolve state with the given value. The Promise state will transition from Pending to Fulfilled.
type PromiseState ¶
type PromiseState int
PromiseState is the state of the Promise.
const ( Pending PromiseState = iota Fulfilled Rejected )
type PropertyAttribute ¶
type PropertyAttribute uint8
PropertyAttribute are the attribute flags for a property on an Object. Typical usage when setting an Object or TemplateObject property, and can also be validated when accessing a property.
const ( // None. None PropertyAttribute = 0 // ReadOnly, ie. not writable. ReadOnly PropertyAttribute = 1 << iota // DontEnum, ie. not enumerable. DontEnum // DontDelete, ie. not configurable. DontDelete )
type StackFrame ¶ added in v0.36.0
type StackFrame struct {
ScriptName string
FunctionName string
// LineNumber and ColumnNumber are 1-based.
LineNumber, ColumnNumber int
IsEval bool
IsConstructor bool
IsWASM bool
IsUserJavaScript bool
}
StackFrame is a frame in the stack trace of a Message.
type Symbol ¶
type Symbol struct {
*Value
}
A Symbol represents a JavaScript symbol (ECMA-262 edition 6).
func SymbolAsyncIterator ¶
func SymbolHasInstance ¶
func SymbolIterator ¶
func SymbolMatch ¶
func SymbolReplace ¶
func SymbolSearch ¶
func SymbolSplit ¶
func SymbolToPrimitive ¶
func SymbolToStringTag ¶
func SymbolUnscopables ¶
func (*Symbol) Description ¶
Description returns the string representation of the symbol, e.g. "Symbol.asyncIterator".
type UnboundScript ¶
type UnboundScript struct {
// contains filtered or unexported fields
}
func (*UnboundScript) CreateCodeCache ¶
func (u *UnboundScript) CreateCodeCache() *CompilerCachedData
Create a code cache from the unbound script.
func (*UnboundScript) Run ¶
func (u *UnboundScript) Run(ctx *Context) (*Value, error)
Run will bind the unbound script to the provided context and run it. If the context provided does not belong to the same isolate that the script was compiled in, Run will panic. If an error occurs, it will be of type `JSError`.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value represents all Javascript values and objects
func JSONParse ¶
JSONParse tries to parse the string and returns it as *Value if successful. Any JS errors will be returned as `JSError`.
Example ¶
package main
import (
"fmt"
v8 "github.com/tommie/v8go"
)
func main() {
ctx := v8.NewContext()
defer ctx.Isolate().Dispose()
defer ctx.Close()
val, _ := v8.JSONParse(ctx, `{"foo": "bar"}`)
fmt.Println(val)
}
Output: [object Object]
func NewValue ¶
NewValue will create a primitive value. Supported values types to create are:
string -> V8::String int32 -> V8::Integer uint32 -> V8::Integer int64 -> V8::BigInt uint64 -> V8::BigInt bool -> V8::Boolean *big.Int -> V8::BigInt
Other pointers are wrapped in a V8::External. JavaScript sees an opaque object, which can e.g. be stored in an internal field with Object.SetInternalField, or passed to a function. The Go value is read back with Value.External. Other types are not supported: a slice or map was probably meant to be converted, and a struct would be copied.
Each call creates a new External, so wrapping the same pointer twice gives two values that are not equal in JavaScript.
V8 keeps the Go value until the External is garbage collected, or the Isolate is disposed. The returned Value keeps the External alive until it is released, like any other Value.
Example (External) ¶
This example exposes a Go strings.Builder to JavaScript as the class StringBuilder. Each JavaScript instance stores its Go object, wrapped in an External, in an internal field.
package main
import (
"fmt"
"strings"
v8 "github.com/tommie/v8go"
)
// This example exposes a Go [strings.Builder] to JavaScript as the class
// StringBuilder. Each JavaScript instance stores its Go object, wrapped in an
// External, in an internal field.
func main() {
iso := v8.NewIsolate()
defer iso.Dispose()
// Each callback releases its arguments, so the objects can be garbage
// collected, and the strings.Builders with them.
constructor := v8.NewFunctionTemplateWithError(iso, func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
defer info.Release()
// Without new, this is the global object, which has no internal
// fields.
this := info.This()
if this.InternalFieldCount() < 1 {
return nil, v8.NewTypeError(iso, "Constructor StringBuilder requires 'new'")
}
ext, err := v8.NewValue(iso, &strings.Builder{})
if err != nil {
return nil, err
}
defer ext.Release()
return nil, this.SetInternalField(0, ext)
})
constructor.InstanceTemplate().SetInternalFieldCount(1)
proto := constructor.PrototypeTemplate()
proto.Set("write", v8.NewFunctionTemplateWithError(iso, func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
defer info.Release()
sb, err := builderFromThis(info)
if err != nil {
return nil, err
}
for _, arg := range info.Args() {
sb.WriteString(arg.String())
}
return nil, nil
}))
proto.Set("toString", v8.NewFunctionTemplateWithError(iso, func(info *v8.FunctionCallbackInfo) (*v8.Value, error) {
defer info.Release()
sb, err := builderFromThis(info)
if err != nil {
return nil, err
}
return v8.NewValue(iso, sb.String())
}))
global := v8.NewObjectTemplate(iso)
global.Set("StringBuilder", constructor)
ctx := v8.NewContext(iso, global)
defer ctx.Close()
v, err := ctx.RunScript(`
const sb = new StringBuilder();
sb.write("Hello, ", "World");
sb.write("!");
sb.toString();`, "builder.js")
if err != nil {
panic(err)
}
fmt.Println(v.String())
// An object can inherit the methods without being created by the
// constructor. It then has no internal field.
_, err = ctx.RunScript(`
const fake = { __proto__: StringBuilder.prototype };
fake.write("oops");`, "fake.js")
fmt.Println(err)
_, err = ctx.RunScript(`StringBuilder()`, "call.js")
fmt.Println(err)
}
// builderFromThis returns the Go object wrapped by the receiver of a method
// call. It returns a TypeError, as built-in methods do, if the receiver was not
// created by the StringBuilder constructor. That includes objects from other
// classes wrapping Go values, so the type is checked.
func builderFromThis(info *v8.FunctionCallbackInfo) (*strings.Builder, error) {
this := info.This()
if this.InternalFieldCount() < 1 {
return nil, v8.NewTypeError(info.Context().Isolate(), "Illegal invocation")
}
field := this.GetInternalField(0)
defer field.Release()
v, _ := field.External()
sb, ok := v.(*strings.Builder)
if !ok {
return nil, v8.NewTypeError(info.Context().Isolate(), "Illegal invocation")
}
return sb, nil
}
Output: Hello, World! TypeError: Illegal invocation TypeError: Constructor StringBuilder requires 'new'
func (*Value) ArrayIndex ¶
ArrayIndex attempts to converts a string to an array index. Returns ok false if conversion fails.
func (*Value) AsException ¶
func (*Value) AsFunction ¶
func (*Value) AsObject ¶
AsObject will cast the value to the Object type. If the value is not an Object then an error is returned. Use `value.Object()` to do the JS equivalent of `Object(value)`.
func (*Value) AsSymbol ¶
AsSymbol will cast the value to the Symbol type. If the value is not a Symbol then an error is returned.
func (*Value) Boolean ¶
Boolean perform the equivalent of `Boolean(value)` in JS. This can never fail.
func (*Value) DetailString ¶
DetailString provide a string representation of this value usable for debugging.
func (*Value) External ¶ added in v0.38.0
External returns the Go value wrapped by NewValue. It returns false if the value is not an External.
func (*Value) Format ¶
Format implements the fmt.Formatter interface to provide a custom formatter primarily to output the detail string (for debugging) with `%+v` verb.
func (*Value) Int32 ¶
Int32 perform the equivalent of `Number(value)` in JS and convert the result to a signed 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-toint32.
func (*Value) Integer ¶
Integer perform the equivalent of `Number(value)` in JS and convert the result to an integer. Negative values are rounded up, positive values are rounded down. NaN is converted to 0. Infinite values yield undefined results.
func (*Value) IsArgumentsObject ¶
IsArgumentsObject returns true if this value is an Arguments object.
func (*Value) IsArray ¶
IsArray returns true if this value is an array. Note that it will return false for a `Proxy` of an array.
func (*Value) IsArrayBuffer ¶
IsArrayBuffer returns true if this value is an `ArrayBuffer`.
func (*Value) IsArrayBufferView ¶
IsArrayBufferView returns true if this value is an `ArrayBufferView`.
func (*Value) IsAsyncFunction ¶
IsAsyncFunc returns true if this value is an async function.
func (*Value) IsBigInt ¶
IsBigInt returns true if this value is a bigint. This is equivalent to `typeof value === 'bigint'` in JS.
func (*Value) IsBigInt64Array ¶
IsBigInt64Array returns true if this value is a `BigInt64Array`.
func (*Value) IsBigIntObject ¶
IsBigIntObject returns true if this value is a BigInt object.
func (*Value) IsBigUint64Array ¶
IsBigUint64Array returns true if this value is a BigUint64Array`.
func (*Value) IsBoolean ¶
IsBoolean returns true if this value is boolean. This is equivalent to `typeof value === 'boolean'` in JS.
func (*Value) IsDataView ¶
IsDataView returns true if this value is a `DataView`.
func (*Value) IsExternal ¶
IsExternal returns true if this value is an `External` object.
func (*Value) IsFalse ¶
IsFalse returns true if this value is false. This is not the same as `!BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `!Boolean(value)` in JS, whereas this checks `value === false`.
func (*Value) IsFloat32Array ¶
IsFloat32Array returns true if this value is a `Float32Array`.
func (*Value) IsFloat64Array ¶
IsFloat64Array returns true if this value is a `Float64Array`.
func (*Value) IsFunction ¶
IsFunction returns true if this value is a function. This is equivalent to `typeof value === 'function'` in JS.
func (*Value) IsGeneratorFunction ¶
Is IsGeneratorFunc returns true if this value is a Generator function.
func (*Value) IsGeneratorObject ¶
IsGeneratorObject returns true if this value is a Generator object (iterator).
func (*Value) IsInt8Array ¶
IsInt8Array returns true if this value is an `Int8Array`.
func (*Value) IsInt16Array ¶
IsInt16Array returns true if this value is an `Int16Array`.
func (*Value) IsInt32Array ¶
IsInt32Array returns true if this value is an `Int32Array`.
func (*Value) IsMapIterator ¶
IsMapIterator returns true if this value is a `Map` Iterator.
func (*Value) IsModuleNamespaceObject ¶
IsModuleNamespaceObject returns true if the value is a `Module` Namespace `Object`.
func (*Value) IsName ¶
IsName returns true if this value is a symbol or a string. This is equivalent to `typeof value === 'string' || typeof value === 'symbol'` in JS.
func (*Value) IsNativeError ¶
IsNativeError returns true if this value is a NativeError.
func (*Value) IsNullOrUndefined ¶
IsNullOrUndefined returns true if this value is either the null or the undefined value. See ECMA-262 4.3.11. and 4.3.12 This is equivalent to `value == null` in JS.
func (*Value) IsNumber ¶
IsNumber returns true if this value is a number. This is equivalent to `typeof value === 'number'` in JS.
func (*Value) IsNumberObject ¶
IsNumberObject returns true if this value is a `Number` object.
func (*Value) IsSetIterator ¶
IsSetIterator returns true if this value is a `Set` Iterator.
func (*Value) IsSharedArrayBuffer ¶
IsSharedArrayBuffer returns true if this value is a `SharedArrayBuffer`.
func (*Value) IsString ¶
IsString returns true if this value is an instance of the String type. See ECMA-262 8.4. This is equivalent to `typeof value === 'string'` in JS.
func (*Value) IsStringObject ¶
IsStringObject returns true if this value is a `String` object.
func (*Value) IsSymbol ¶
IsSymbol returns true if this value is a symbol. This is equivalent to `typeof value === 'symbol'` in JS.
func (*Value) IsSymbolObject ¶
IsSymbolObject returns true if this value is a `Symbol` object.
func (*Value) IsTrue ¶
IsTrue returns true if this value is true. This is not the same as `BooleanValue()`. The latter performs a conversion to boolean, i.e. the result of `Boolean(value)` in JS, whereas this checks `value === true`.
func (*Value) IsTypedArray ¶
IsTypedArray returns true if this value is one of TypedArrays.
func (*Value) IsUint8Array ¶
IsUint8Array returns true if this value is an `Uint8Array`.
func (*Value) IsUint8ClampedArray ¶
IsUint8ClampedArray returns true if this value is an `Uint8ClampedArray`.
func (*Value) IsUint16Array ¶
IsUint16Array returns true if this value is an `Uint16Array`.
func (*Value) IsUint32Array ¶
IsUint32Array returns true if this value is an `Uint32Array`.
func (*Value) IsUndefined ¶
IsUndefined returns true if this value is the undefined value. See ECMA-262 4.3.10.
func (*Value) IsWasmModuleObject ¶
IsWasmModuleObject returns true if this value is a `WasmModuleObject`.
func (*Value) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (*Value) Object ¶
Object perform the equivalent of Object(value) in JS. To just cast this value as an Object use AsObject() instead.
func (*Value) Release ¶
func (v *Value) Release()
Release this value. Using the value after calling this function will result in undefined behavior.
func (*Value) SameValue ¶
SameValue returns true if the other value is the same value. This is equivalent to `Object.is(v, other)` in JS.
func (*Value) SharedArrayBufferGetContents ¶
func (*Value) StrictEquals ¶ added in v0.34.0
func (*Value) String ¶
String perform the equivalent of `String(value)` in JS. Primitive values are returned as-is, objects will return `[object Object]` and functions will print their definition.
func (*Value) Uint32 ¶
Uint32 perform the equivalent of `Number(value)` in JS and convert the result to an unsigned 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-touint32.
type ValueError ¶
A ValueError can be returned from a FunctionCallbackWithError, and its value will be thrown as an exception in V8.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
deps
|
|
|
include
Package include holds C++ header files.
|
Package include holds C++ header files. |
|
include/cppgc
Package cppgc holds C++ header files.
|
Package cppgc holds C++ header files. |
|
include/cppgc/internal
Package internal holds C++ header files.
|
Package internal holds C++ header files. |
|
include/libplatform
Package libplatform holds C++ header files.
|
Package libplatform holds C++ header files. |
|
include_libcxx
Package include_libcxx holds C++ header files.
|
Package include_libcxx holds C++ header files. |
|
include_libcxx/__algorithm
Package __algorithm holds C++ header files.
|
Package __algorithm holds C++ header files. |
|
include_libcxx/__atomic
Package __atomic holds C++ header files.
|
Package __atomic holds C++ header files. |
|
include_libcxx/__atomic/support
Package support holds C++ header files.
|
Package support holds C++ header files. |
|
include_libcxx/__bit
Package __bit holds C++ header files.
|
Package __bit holds C++ header files. |
|
include_libcxx/__charconv
Package __charconv holds C++ header files.
|
Package __charconv holds C++ header files. |
|
include_libcxx/__chrono
Package __chrono holds C++ header files.
|
Package __chrono holds C++ header files. |
|
include_libcxx/__compare
Package __compare holds C++ header files.
|
Package __compare holds C++ header files. |
|
include_libcxx/__concepts
Package __concepts holds C++ header files.
|
Package __concepts holds C++ header files. |
|
include_libcxx/__condition_variable
Package __condition_variable holds C++ header files.
|
Package __condition_variable holds C++ header files. |
|
include_libcxx/__configuration
Package __configuration holds C++ header files.
|
Package __configuration holds C++ header files. |
|
include_libcxx/__coroutine
Package __coroutine holds C++ header files.
|
Package __coroutine holds C++ header files. |
|
include_libcxx/__cstddef
Package __cstddef holds C++ header files.
|
Package __cstddef holds C++ header files. |
|
include_libcxx/__cxx03
Package __cxx03 holds C++ header files.
|
Package __cxx03 holds C++ header files. |
|
include_libcxx/__cxx03/__algorithm
Package __algorithm holds C++ header files.
|
Package __algorithm holds C++ header files. |
|
include_libcxx/__cxx03/__atomic
Package __atomic holds C++ header files.
|
Package __atomic holds C++ header files. |
|
include_libcxx/__cxx03/__bit
Package __bit holds C++ header files.
|
Package __bit holds C++ header files. |
|
include_libcxx/__cxx03/__chrono
Package __chrono holds C++ header files.
|
Package __chrono holds C++ header files. |
|
include_libcxx/__cxx03/__condition_variable
Package __condition_variable holds C++ header files.
|
Package __condition_variable holds C++ header files. |
|
include_libcxx/__cxx03/__configuration
Package __configuration holds C++ header files.
|
Package __configuration holds C++ header files. |
|
include_libcxx/__cxx03/__debug_utils
Package __debug_utils holds C++ header files.
|
Package __debug_utils holds C++ header files. |
|
include_libcxx/__cxx03/__exception
Package __exception holds C++ header files.
|
Package __exception holds C++ header files. |
|
include_libcxx/__cxx03/__functional
Package __functional holds C++ header files.
|
Package __functional holds C++ header files. |
|
include_libcxx/__cxx03/__fwd
Package __fwd holds C++ header files.
|
Package __fwd holds C++ header files. |
|
include_libcxx/__cxx03/__ios
Package __ios holds C++ header files.
|
Package __ios holds C++ header files. |
|
include_libcxx/__cxx03/__iterator
Package __iterator holds C++ header files.
|
Package __iterator holds C++ header files. |
|
include_libcxx/__cxx03/__locale_dir
Package __locale_dir holds C++ header files.
|
Package __locale_dir holds C++ header files. |
|
include_libcxx/__cxx03/__locale_dir/locale_base_api
Package locale_base_api holds C++ header files.
|
Package locale_base_api holds C++ header files. |
|
include_libcxx/__cxx03/__math
Package __math holds C++ header files.
|
Package __math holds C++ header files. |
|
include_libcxx/__cxx03/__memory
Package __memory holds C++ header files.
|
Package __memory holds C++ header files. |
|
include_libcxx/__cxx03/__mutex
Package __mutex holds C++ header files.
|
Package __mutex holds C++ header files. |
|
include_libcxx/__cxx03/__numeric
Package __numeric holds C++ header files.
|
Package __numeric holds C++ header files. |
|
include_libcxx/__cxx03/__ostream
Package __ostream holds C++ header files.
|
Package __ostream holds C++ header files. |
|
include_libcxx/__cxx03/__random
Package __random holds C++ header files.
|
Package __random holds C++ header files. |
|
include_libcxx/__cxx03/__string
Package __string holds C++ header files.
|
Package __string holds C++ header files. |
|
include_libcxx/__cxx03/__support
Package __support holds C++ header files.
|
Package __support holds C++ header files. |
|
include_libcxx/__cxx03/__support/ibm
Package ibm holds C++ header files.
|
Package ibm holds C++ header files. |
|
include_libcxx/__cxx03/__support/xlocale
Package xlocale holds C++ header files.
|
Package xlocale holds C++ header files. |
|
include_libcxx/__cxx03/__system_error
Package __system_error holds C++ header files.
|
Package __system_error holds C++ header files. |
|
include_libcxx/__cxx03/__thread
Package __thread holds C++ header files.
|
Package __thread holds C++ header files. |
|
include_libcxx/__cxx03/__thread/support
Package support holds C++ header files.
|
Package support holds C++ header files. |
|
include_libcxx/__cxx03/__tuple
Package __tuple holds C++ header files.
|
Package __tuple holds C++ header files. |
|
include_libcxx/__cxx03/__type_traits
Package __type_traits holds C++ header files.
|
Package __type_traits holds C++ header files. |
|
include_libcxx/__cxx03/__utility
Package __utility holds C++ header files.
|
Package __utility holds C++ header files. |
|
include_libcxx/__cxx03/__variant
Package __variant holds C++ header files.
|
Package __variant holds C++ header files. |
|
include_libcxx/__cxx03/experimental
Package experimental holds C++ header files.
|
Package experimental holds C++ header files. |
|
include_libcxx/__cxx03/ext
Package ext holds C++ header files.
|
Package ext holds C++ header files. |
|
include_libcxx/__debug_utils
Package __debug_utils holds C++ header files.
|
Package __debug_utils holds C++ header files. |
|
include_libcxx/__exception
Package __exception holds C++ header files.
|
Package __exception holds C++ header files. |
|
include_libcxx/__expected
Package __expected holds C++ header files.
|
Package __expected holds C++ header files. |
|
include_libcxx/__filesystem
Package __filesystem holds C++ header files.
|
Package __filesystem holds C++ header files. |
|
include_libcxx/__flat_map
Package __flat_map holds C++ header files.
|
Package __flat_map holds C++ header files. |
|
include_libcxx/__flat_set
Package __flat_set holds C++ header files.
|
Package __flat_set holds C++ header files. |
|
include_libcxx/__format
Package __format holds C++ header files.
|
Package __format holds C++ header files. |
|
include_libcxx/__functional
Package __functional holds C++ header files.
|
Package __functional holds C++ header files. |
|
include_libcxx/__fwd
Package __fwd holds C++ header files.
|
Package __fwd holds C++ header files. |
|
include_libcxx/__ios
Package __ios holds C++ header files.
|
Package __ios holds C++ header files. |
|
include_libcxx/__iterator
Package __iterator holds C++ header files.
|
Package __iterator holds C++ header files. |
|
include_libcxx/__locale_dir
Package __locale_dir holds C++ header files.
|
Package __locale_dir holds C++ header files. |
|
include_libcxx/__locale_dir/locale_base_api
Package locale_base_api holds C++ header files.
|
Package locale_base_api holds C++ header files. |
|
include_libcxx/__locale_dir/support
Package support holds C++ header files.
|
Package support holds C++ header files. |
|
include_libcxx/__locale_dir/support/no_locale
Package no_locale holds C++ header files.
|
Package no_locale holds C++ header files. |
|
include_libcxx/__math
Package __math holds C++ header files.
|
Package __math holds C++ header files. |
|
include_libcxx/__mdspan
Package __mdspan holds C++ header files.
|
Package __mdspan holds C++ header files. |
|
include_libcxx/__memory
Package __memory holds C++ header files.
|
Package __memory holds C++ header files. |
|
include_libcxx/__memory_resource
Package __memory_resource holds C++ header files.
|
Package __memory_resource holds C++ header files. |
|
include_libcxx/__mutex
Package __mutex holds C++ header files.
|
Package __mutex holds C++ header files. |
|
include_libcxx/__new
Package __new holds C++ header files.
|
Package __new holds C++ header files. |
|
include_libcxx/__numeric
Package __numeric holds C++ header files.
|
Package __numeric holds C++ header files. |
|
include_libcxx/__ostream
Package __ostream holds C++ header files.
|
Package __ostream holds C++ header files. |
|
include_libcxx/__pstl
Package __pstl holds C++ header files.
|
Package __pstl holds C++ header files. |
|
include_libcxx/__pstl/backends
Package backends holds C++ header files.
|
Package backends holds C++ header files. |
|
include_libcxx/__pstl/cpu_algos
Package cpu_algos holds C++ header files.
|
Package cpu_algos holds C++ header files. |
|
include_libcxx/__random
Package __random holds C++ header files.
|
Package __random holds C++ header files. |
|
include_libcxx/__ranges
Package __ranges holds C++ header files.
|
Package __ranges holds C++ header files. |
|
include_libcxx/__stop_token
Package __stop_token holds C++ header files.
|
Package __stop_token holds C++ header files. |
|
include_libcxx/__string
Package __string holds C++ header files.
|
Package __string holds C++ header files. |
|
include_libcxx/__support
Package __support holds C++ header files.
|
Package __support holds C++ header files. |
|
include_libcxx/__support/ibm
Package ibm holds C++ header files.
|
Package ibm holds C++ header files. |
|
include_libcxx/__support/xlocale
Package xlocale holds C++ header files.
|
Package xlocale holds C++ header files. |
|
include_libcxx/__system_error
Package __system_error holds C++ header files.
|
Package __system_error holds C++ header files. |
|
include_libcxx/__thread
Package __thread holds C++ header files.
|
Package __thread holds C++ header files. |
|
include_libcxx/__thread/support
Package support holds C++ header files.
|
Package support holds C++ header files. |
|
include_libcxx/__tuple
Package __tuple holds C++ header files.
|
Package __tuple holds C++ header files. |
|
include_libcxx/__type_traits
Package __type_traits holds C++ header files.
|
Package __type_traits holds C++ header files. |
|
include_libcxx/__utility
Package __utility holds C++ header files.
|
Package __utility holds C++ header files. |
|
include_libcxx/__variant
Package __variant holds C++ header files.
|
Package __variant holds C++ header files. |
|
include_libcxx/__vector
Package __vector holds C++ header files.
|
Package __vector holds C++ header files. |
|
include_libcxx/experimental
Package experimental holds C++ header files.
|
Package experimental holds C++ header files. |
|
include_libcxx/experimental/__simd
Package __simd holds C++ header files.
|
Package __simd holds C++ header files. |
|
include_libcxx/ext
Package ext holds C++ header files.
|
Package ext holds C++ header files. |
|
include_libcxxabi
Package include_libcxxabi holds C++ header files.
|
Package include_libcxxabi holds C++ header files. |
|
android_amd64
module
|
|
|
android_arm64
module
|
|
|
darwin_amd64
module
|
|
|
darwin_arm64
module
|
|
|
linux_amd64
module
|
|
|
linux_arm64
module
|
|
|
windows_amd64
module
|