1

I want to get a JavaScript variable from https://admin.booking.com/hotel/hoteladmin in head > script > var token.

enter image description here

I don't know how this variable is set by the browser because when I get this page from Mechanize I get:

var token = '' || 'empty-token',

Here is the code I use to GET this page:

login_url = "https://admin.booking.com/hotel/hoteladmin"
agent = Mechanize.new
agent.verify_mode= OpenSSL::SSL::VERIFY_NONE
page = agent.get(login_url)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ZazOufUmI
  • 3,212
  • 6
  • 37
  • 67
  • Not knowing your use case, I'd say you are using the wrong tools. I'd probably favor using Watir and Selenium to interact directly with the browser and write some javascript to directly access the desired value. – Jeff Price Apr 16 '15 at 18:32
  • @JeffPrice I want to retrieve the token because it is use as the csrf_token in the form I want to submit using Mechanize – ZazOufUmI Apr 16 '15 at 18:53
  • It's set by a javascript cookie. It can be done in mechanize but you can save yourself a headache by switching to Watir. – pguardiario Apr 17 '15 at 23:20
  • @pguardiario I would prefer do it with Mechanize if it's possible, how would you do that ? I'm using C9IDE for dev and watir doesn't seems to work well in it, I tried multiple times with mutliple versions without success... – ZazOufUmI Apr 18 '15 at 06:15
  • It's too complicated to explain here. I recommend asking a question about Watir and C9IDE – pguardiario Apr 18 '15 at 06:57

1 Answers1

0

If you want to access this token via JavaScript in mechanize/watir, you need to be able to access it with your browsers developers tools as well.

Unfortunately the variable itself is enclosed in a scope, which makes it impossible to access it just like that. You can read more about the many different types of scopes in JS in this excellent post: What is the scope of variables in JavaScript?

Now to answer your question. Sure, it would be possible to extract the token itself, but you would have to do it in a dirty manner. You would have to wait untill all JS is executed on the page and then take the document body and extract it somehow - one way could be RegExp.

EDIT: Mechanize does according to a a few other answers here on SO not execute JS, which is why you need a gem that drives a browser (watir is a great example), but that drives us back to the problem described above.

Community
  • 1
  • 1
Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
  • Thanks Jan ! What I don't get is that even if I disable Javascript on my browser, it create this variable... I don't get how it's possible – ZazOufUmI Apr 17 '15 at 07:52