Search code examples
javascriptrubyselenium-webdriverwatir

How to add and execute a JavaScript function to a web page with Watir


How can I add a JavaScript function to a given webpage, execute it, and then read its results with Watir?

require 'watir'
myfn = %<
  function samsFunction () {
    var samsBigVariable;
    window.samsBigVariable = "my secret goes here";
  };
  samsFunction();
>.gsub(/\s+/, ' ').strip
b = Watir::Browser.new :firefox
b.goto "google.com"
b.execute_script myfn
b.execute_script "window.samsBigVariable"
 => nil

Executing the same JavaScript in the console results in the variable being set and returned when called. What is different about execute_script?


Solution

  • You need to explicitly return the value:

    b.execute_script "return window.samsBigVariable"
    #=> "my secret goes here"