1

I'm trying to interact with website with no JQuery by using Watir and PhantomJS.

browser = Watir::Browser.new :phantomjs, :args => ['--ignore-ssl-errors=yes']
browser.goto 'http://putlocker.is/'

browser.execute_script(    
  "var the_script = document.createElement('script');
  the_script.setAttribute('src','http://code.jquery.com/jquery-1.11.0.min.js');
  document.body.appendChild(the_script);"
)

browser.execute_script('$("div").hide();')

With Firefox instead of PhantomJS it works fine - JQuery is loaded on a page and I can manage elements using JQuery. But PhantomJS raises this error:

{"errorMessage":"Can't find variable: $","request":{"headers":{"Accept":"application/json","Accept-Encoding":"gzip;q=1.0,deflate;q=0.6,identity;q=0.3","Connection":"close","Content-Length":"41","Content-Type":"application/json; charset=utf-8","Host":"127.0.0.1:8910","User-Agent":"Ruby"},"httpVersion":"1.1","method":"POST","post":"{\"script\":\"$(\\"div\\").hide();\",\"args\":[]}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/84f7d6d0-7035-11e4-a8b8-85c94f571d8e/execute"}} (ReqHand)

I guess this issue is somehow related to this question: Can't find variable - PhantomJS. But how to change Watir code so that it works?

Community
  • 1
  • 1
Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70

1 Answers1

2

PhantomJS seems to behave differently from Firefox. It may be the case that PhantomJS is simply faster, it may also be that PhantomJS doesn't wait for the script to download. In either case you need to wait for the script to load. You can of course wait a static amount of time, but it is always better to wait just the right amount of time.

browser.execute_script(injectScript)
Watir::Wait.until { browser.execute_script("return !!window.jQuery") }
browser.execute_script('$("div").hide();')
Artjom B.
  • 61,146
  • 24
  • 125
  • 222