Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Runtime.SetGlobalObject() method. #654

Merged
merged 1 commit into from
Jan 25, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
@@ -2377,6 +2377,12 @@ func (r *Runtime) GlobalObject() *Object {
return r.globalObject
}

// SetGlobalObject sets the global object to the given object.
// Note, any existing references to the previous global object will continue to reference that object.
func (r *Runtime) SetGlobalObject(object *Object) {
r.globalObject = object
}

// Set the specified variable in the global context.
// Equivalent to running "name = value" in non-strict mode.
// The value is first converted using ToValue().
66 changes: 66 additions & 0 deletions runtime_test.go
Original file line number Diff line number Diff line change
@@ -1087,6 +1087,72 @@ func TestRuntime_ExportToObject(t *testing.T) {
}
}

func TestRuntime_SetGlobalObject(t *testing.T) {
vm := New()

_, err := vm.RunString(`var myVar = 123;`)
if err != nil {
t.Fatal(err)
}

oldGlobalObject := vm.GlobalObject()

newGlobalObject, err := vm.RunString(`({oldGlobalReference:globalThis});`)
if err != nil {
t.Fatal(err)
}

vm.SetGlobalObject(newGlobalObject.(*Object))

if vm.GlobalObject() != newGlobalObject {
t.Fatal("Expected global object to be new object")
}

if vm.GlobalObject().Get("myVar") != nil {
t.Fatal("Expected myVar to be undefined")
}

oldGlobalReference := vm.GlobalObject().Get("oldGlobalReference")
if oldGlobalReference == nil {
t.Fatal("Expected oldGlobalReference to be defined")
}

if oldGlobalReference != oldGlobalObject {
t.Fatal("Expected reference to be to old global object")
}
}

func TestRuntime_SetGlobalObject_Proxy(t *testing.T) {
vm := New()

globalObject := vm.GlobalObject()

globalObjectProxy := vm.NewProxy(globalObject, &ProxyTrapConfig{
Get: func(target *Object, property string, receiver Value) (value Value) {
if target != globalObject {
t.Fatal("Expected target to be global object")
}

if property != "testing" {
t.Fatal("Expected property to be 'testing'")
}

return valueTrue
},
})

vm.SetGlobalObject(vm.ToValue(globalObjectProxy).(*Object))

ret, err := vm.RunString("testing")
if err != nil {
t.Fatal(err)
}

if ret != valueTrue {
t.Fatal("Expected return value to equal true")
}
}

func ExampleAssertFunction() {
vm := New()
_, err := vm.RunString(`