sourcegraph / webloop

WebLoop: Scriptable, headless WebKit with a Go API. Like PhantomJS, but for Go.
https://sourcegraph.com/github.com/sourcegraph/webloop
BSD 3-Clause "New" or "Revised" License
1.37k stars 84 forks source link

How to return read javascript arrays in Go? #11

Closed bitforth closed 9 years ago

bitforth commented 9 years ago

I'm coming from the CasperJS world, so bare with me if the question doesn't make any sense.

in CasperJs if I do:

var links = this.evaluate(function(){
return document.querySelectorAll('a');
});

that's going to return the list of links within the headless browser, back to the casperjs environment.

I tried to do the same thing with webloop, but obviously didn't work as I was expecting it (Had the hunch it wouldn't, but wanted to give it a try anyways).

res, err := view.EvaluateJavaScript(var links = document.getElementsByTagName(\"a\"); for(var i = 0; i < links.length; ++i) { links[i].innerHTML }; ")

Just returns the innerHTML of the last element. I thought about building and object within javascript, and then stringify that object within the function, just for the string to be parsed by GoLang, but I'm not sure if that's the right way to go about this, or if there's a function provided within Webloop to accomplish this task.

Thanks

sqs commented 9 years ago

I think your intuition is right about returning a JSON string from JS that you re-parse in Go. I actually forget how gojs, the underlying lib used to call into and read from JS, works with values. It may be able to convert JS objects to Go map[string]interface{}, so you could give that a try, too.

Eithe way, that for-loop expression won't do what you want. Unless there's some special or undefined behavior with respect to return values I'm not understanding, the "return value" of the for-loop statement is the value of the last loop body. You can try it out in node or the JS console:

var a=[1,2,3];for(var i=0;i<a.length;i++){a[i]}
3

(not [1,2,3])

bitforth commented 9 years ago

Awesome, yes I noticed that and then I wrote the equivalent code in the javascript console of Chrome, and I noticed that the "return" value was always the last one of the for-loop statement.

Thank you for taking the time to reply, and doing it so quickly! I was able to output a stringified JSON object back to the terminal, and parse it from there. I will try gojs later today, thanks!