如何使用Cucumber\Ruby\PageObject从浏览器JavaScript全局变量中获取值?

如何使用Cucumber\Ruby\PageObject从浏览器JavaScript全局变量中获取值?,javascript,ruby,automated-tests,cucumber,pageobjects,Javascript,Ruby,Automated Tests,Cucumber,Pageobjects,在我的自动测试中,我需要获取JavaScript全局变量的值 例如,从以下HTML获取全局_var值: <!DOCTYPE html> <html> <body> <script> var global_var = "John Smith" </script> <h2>Test JavaScript</h2> <button type="button" onclick="document.getEleme

在我的自动测试中,我需要获取JavaScript全局变量的值

例如,从以下HTML获取全局_var值:

<!DOCTYPE html>
<html>
<body>
<script>
var global_var = "John Smith"
</script>
<h2>Test JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = global_var">
Click me to display "global_var" value.</button>

<p id="demo"></p>

</body>
</html> 
这就是我所尝试的:


browser.execute_script“document.global_var”

您可以尝试以下Ruby\PageObject代码:

class TestPage
  include PageObject

  page_url ("<system url that you are testing>")

  def get_global_variable_value
    value = self.browser.execute_script("return window.global_var")
    puts  "Value of "global_var" is: " + value
  end
end ```

您可以尝试以下Ruby\PageObject代码:

class TestPage
  include PageObject

  page_url ("<system url that you are testing>")

  def get_global_variable_value
    value = self.browser.execute_script("return window.global_var")
    puts  "Value of "global_var" is: " + value
  end
end ```

更好的是,您可以通过以下方式轻松地将get_global_variable_值用于任何全局变量名:

class TestPage
  include PageObject

  page_url ("<system url that you are testing>")

  def get_global_variable_value var_name
    value = self.browser.execute_script("return window.#{var_name}")
    puts  "Value of #{var_name} is: " + value
  end
end

更好的是,您可以通过以下方式轻松地将get_global_variable_值用于任何全局变量名:

class TestPage
  include PageObject

  page_url ("<system url that you are testing>")

  def get_global_variable_value var_name
    value = self.browser.execute_script("return window.#{var_name}")
    puts  "Value of #{var_name} is: " + value
  end
end

你能分享你已经尝试过的吗?谢谢,这是我的第一个问题,所以我忽略了添加我已经尝试过的内容。你能分享你已经尝试过的内容吗?谢谢,这是我的第一个问题,所以我忽略了添加我已经尝试过的内容。