简体   繁体   中英

How to get a value from browser JavaScript global variable using Cucumber\Ruby\PageObject?

In my automatic tests I need to get a value of JavaScript global variable.

For example, get a value of global_var from the following HTML:

<!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> 

This is what I tried:

browser.execute_script(“document.global_var”)

Even better, you could easily make the get_global_variable_value to be used for any global variable name by:

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

You could try the following Ruby\\PageObject code:

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 ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM