如何将JavaScript函数添加到给定网页,执行它,然后使用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
在控制台中执行相同的JavaScript会导致设置变量并在调用时返回。有什么不同execute_script
?
答案 0 :(得分:2)
您需要显式返回值:
b.execute_script "return window.samsBigVariable"
#=> "my secret goes here"