dop251 / goja

ECMAScript/JavaScript engine in pure Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I capture console logs from inside VM

vishaNagpal opened this issue · comments

Hello,
For some requirements, I need to return the console logs.
Had it been pure javascript, I could have done something like the below :
var list = []; window.console.log = (val)=>{list.push(val)}
// list will now contain all the console logs inside it
I tried to add a custom method like print('something here') but was unable to define it. Any help would be appreciated.
Thanks

I have implemented something like below :

script := `
		var aa = 23
		print(aa)
		print("Print -> "+(aa+5))
	`
val, _ := vm.RunString(script)

Here, I have created one custom method (print method) like console.log () I want to store values returned by the print methods inside a list & then return that list.
Can you guide on how can expose this list to inside the custom print method?

Thanks in advance

Hi, I'm not sure if I understood exactly what you try to achieve, but the following exemple may put you on the right path.

var script = `
console.log = val => {list.push(val)}
console.log('foo')
console.log(123)
console.log('bar')
print(list) // print foo, 123, bar
`

rt := goja.New()

console := rt.NewObject()
if err := rt.Set("console", console); err != nil {
	panic(err)
}

list := make([]string, 0)
if err := rt.Set("list", &list); err != nil {
	panic(err)
}

print := func(value goja.Value) {
	fmt.Println(value.String())
}

if err := rt.Set("print", print); err != nil {
	panic(err)
}

_, err := rt.RunString(script)
if err != nil {
	panic(err)
}

fmt.Println(list) // print [foo 123 bar]

Hi, thanks for taking the time in responding.
The approach you mentioned could not be used in my scenario as explicitly redefining the console.log is still possible every time I am calling rt.RunString but this way my RunProgram or RunString will not be returning my result as well as the collection of these log statements.
I found a workaround specific to my problem. Will be happy to share the PR here for your feedback as well. Let me know if you would want me to touch up some more aspect of this.
PR raised here

Just had a look at the example you made, what preventing you to set a log function that append to a slice the value passed in parameter ?

var script = `
var a = 5;
log("Consoling from log method - statement 1")
log("Consoling from log method - statement 2")
log("Variable value "+ (a+5))
`

rt := goja.New()

logs := make([]goja.Value, 0)

log := func(value goja.Value) {
	logs = append(logs, value)
}

if err := rt.Set("log", log); err != nil {
	panic(err)
}

_, err := rt.RunString(script)
if err != nil {
	panic(err)
}

fmt.Println(logs) // [Consoling from log method - statement 1 Consoling from log method - statement 2 Variable value 10]