Skip to content

Commit

Permalink
Merge pull request #654 from Hakkin/SetGlobalObject
Browse files Browse the repository at this point in the history
Add Runtime.SetGlobalObject() method.
  • Loading branch information
dop251 authored Jan 25, 2025
2 parents 46d383d + 436e551 commit 12bd88c
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
6 changes: 6 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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().
Expand Down
66 changes: 66 additions & 0 deletions runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(`
Expand Down

0 comments on commit 12bd88c

Please sign in to comment.