# Variable not receiving value from javascript

**URL:** <https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611>\
**Category:** Web Testing\
**Tags:** katalon-studio\
**Created:** [April 22, 2019, 9:18pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611 "2019-04-22T21:18:32Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 22, 2019, 9:18pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/1 "2019-04-22T21:18:32Z")

</div>

I have the following execute javascript statement in my test:

```auto
WebUI.executeJavaScript('''
  var title_cells = document.querySelectorAll(".views-table tbody tr td.views-field-title");
  title_cells.forEach(function(cell) { 
    if (cell.innerHTML.includes("AUD Entitlement Product")) { 
      return cell.innerHTML; 
    } 
   })
''', null)

```

This successfully returns the correct value. However, if I try to capture it in a variable using:

```auto
String audduration = WebUI.executeJavaScript('''
  var title_cells = document.querySelectorAll(".views-table tbody tr td.views-field-title");
  title_cells.forEach(function(cell) { 
    if (cell.innerHTML.includes("AUD Entitlement Product")) { 
      return cell.innerHTML; 
    } 
})
''', null)

```

the resulting value in “audduration” is null and doesn’t equal what the javascript is returning. So the "String audduration = " part of the statement is not working. Any ideas on what might be wrong?

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 22, 2019, 9:37pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/2 "2019-04-22T21:37:43Z")

</div>

Well, the code is assuming that the forEach loop is going to succeed. It may not. And if it doesn’t succeed, it will return `undefined` (which I believe may get translated to `null` in Groovy).

Background: When Groovy wraps your JS and passes it to the browser, it is inserted into an anonymous function like this:

```java
WebUI.executeJavaScript('alert("hey!");', null)

```

// – becomes – //

```javascript
function() {
  alert("hey!");
}();

```

And the result of a function that does not return anything, is `undefined` – which is exactly what that IIFE above would do.

So, question is, are you seeing the code returning `undefined`?

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 22, 2019, 9:59pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/3 "2019-04-22T21:59:08Z")

</div>

Oh wait… my bad…

You can’t exit early from `forEach`. You could use a traditional `for` loop or try `Array.every` / `Array.some`

---

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 22, 2019, 10:01pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/4 "2019-04-22T22:01:26Z")

</div>

I don’t know what " You can’t exit early from `forEach` . You could use a traditional `for` loop or try `Array.every` / `Array.some`" means, but I’ll ask my developer.

Regarding your first comment, the code returns the correct value, not “undefined”. But when it tries to store it in the variable, it fails to do so.

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 22, 2019, 10:02pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/5 "2019-04-22T22:02:41Z")

</div>

By “exit early” I’m referring to your return statement.

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 22, 2019, 10:05pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/6 "2019-04-22T22:05:16Z")

</div>

Show your “developer” this…

 ![image](https://europe1.discourse-cdn.com/katalon/original/2X/5/50263f823f4ef95647e9aff81c23dbd521b4e93a.png)

> **[Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description)**
>
> The forEach() method of Array instances executes a provided function once
> for each array element.

> <https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function>

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 22, 2019, 10:09pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/7 "2019-04-22T22:09:04Z")

</div>

> [@Jeff\_Sharp](#):
>
> Regarding your first comment, the code returns the correct value, not “undefined”

Understand this: `undefined` is what JavaScript returns from a function that returns no specified value. FACT. However, in Groovy, `undefined` has no meaning so it likely translates it to `null` which is a workable solution to the problem.

---

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 22, 2019, 10:11pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/8 "2019-04-22T22:11:29Z")

</div>

“undefined” is not being returned. We were able to output the value returned from the javascript and it is the correct value, which is “18”.

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 3:10am UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/9 "2019-04-23T03:10:46Z")

</div>

> [@Jeff\_Sharp](#):
>
> “undefined” is not being returned.

It is, Jeff, trust me. That’s how JavaScript works.

There is only one way _ **I can think of** _ for your `forEach` to be behaving differently: your “developer” has hijacked (overwritten) the `Array.forEach` prototype. Doubtful.

Try this. And before you run this code, be sure you understand what YOU are saying compared to what I am saying. This code backs up what I am saying but runs counter to what you are saying.

```auto
    String js = '''
      [1,2,3,4,5].forEach(function(n) {
        if(n === 3) {
          return n; // WILL NOT WORK
        }
      });
    '''
    int n = WebUI.executeJavaScript(js, null)
    println "result: " + n

```

That should fail with an error complaining about casting `null` to an `int` – and rightly so. It’s broken code.

Now try this:

```auto
    String js = '''
      [1,2,3,4,5].forEach(function(n) {
        if(n === 3) {
          return n; // WILL NOT WORK
        }
      });
      return 99;
    '''
    int n = WebUI.executeJavaScript(js, null)
    println "result: " + n

```

You’ll get `99` printed to the console. If you’ve understood what I was saying, it proves _you cannot return a value from inside a genuine_ `Array.forEach` method. PERIOD.

Now, to answer your question (implied in the title of your post) - “Variable not receiving value from javascript”

1. Your code as listed returns `undefined`.
2. Groovy turns `undefined` into `null`
3. You then assign `null` to `audduration`
4. So your variable **_is_** receiving a value from JavaScript (just not the value you’re expecting because your code is invalid/not doing what you thought.)

---

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 23, 2019, 2:57pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/10 "2019-04-23T14:57:03Z")

</div>

After reviewing the code I initially submitted, it appears I pasted the wrong js. This is the code that is returning the correct value.

var title\_cells = document.querySelectorAll(’.views-table tbody tr td.views-field-title’); title\_cells.forEach(function(cell) {  
if (cell.innerHTML.includes(‘AUD Entitlement Product’)) {  
console.log(cell.nextElementSibling.innerHTML);  
}  
});  
, null)

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 3:01pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/11 "2019-04-23T15:01:25Z")

</div>

> [@Jeff\_Sharp](#):
>
> This is the code that is returning the correct value.

That code doesn’t return anything.

---

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 23, 2019, 3:19pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/12 "2019-04-23T15:19:36Z")

</div>

Yeah, because you’re not running it against the page on my website so there is no data for it to return. When run against the table shown in the attachment, it returns “2”, which is the correct value.

 ![59%20AM](https://europe1.discourse-cdn.com/katalon/original/2X/d/de20051598b405fc721975e048297d1e8f3ac51e.png)

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 3:49pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/13 "2019-04-23T15:49:13Z")

</div>

> [@Jeff\_Sharp](#):
>
> Yeah, because you’re not running it against the page on my website so there is no data for it to return.

1. I’m not running it anywhere, except in my head.
2. That code does not _return_ 2, it _prints_ 2 to the console. Printing 2 and returning 2 a very different things.

> [@](#):
>
> … so there is no data for it to return.

Regardless, there is no return statement so it cannot return anything (except undefined when called from Groovy).

 ![image](https://europe1.discourse-cdn.com/katalon/original/2X/e/e070d01e4085e5a2b1facde94b87bb0479c21123.png)

Jeff, I’m sorry, but if you are not going to listen to what I’m trying to teach you, I need to bow out of this cyclic (and frankly pretty pointless) conversation.

By way of courtesy, I’ll make a call out to a few other “code heads”, perhaps they can steer you straight:

@devalex88, @ThanhTo @Brandon_Hein @Marek_Melocik, @Andrej_Podhajsky

Good luck

---

<div class="post-metadata">

**Author:** ![Jeff\_Sharp](https://avatars.discourse-cdn.com/v4/letter/j/a5b964/32.png) [@Jeff\_Sharp](https://forum.katalon.com/u/Jeff_Sharp)\
**Post date:** [April 23, 2019, 3:54pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/14 "2019-04-23T15:54:26Z")

</div>

I’m just the middle man between you and the developer I’m working with. I don’t know javascript nor do I understand it. I’m just relaying here. Also, I’m not trying to learn javascript right now, I’m just trying to get a value into a variable. Thanks.

---

<div class="post-metadata">

**Author:** ![Brandon\_Hein](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/brandon_hein/32/1092_2.png) [@Brandon\_Hein](https://forum.katalon.com/u/Brandon_Hein)\
**Post date:** [April 23, 2019, 4:26pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/15 "2019-04-23T16:26:32Z")

</div>

I’m by no means a JS expert but I have a few suggestions that may help you narrow down the issue:

1.) Try something simple, like:

`String test = WebUI.executeJavaScript("return 'Hello world!';", null);`

If you get the appropriate value in ‘test’, then you know that it’s a problem with your JS, and not the WebUI method call.

2.) Try executing your JS directly through WebDriver, instead of the WebUI API:

```
WebDriver driver = DriverFactory.getWebDriver();
JavascriptExecutor executor = (JavascriptExecutor)driver;
String audduration = executor.executeScript("var title_cells = document.querySelectorAll('.views-table tbody tr td.views-field-title');
  title_cells.forEach(function(cell) { 
    if (cell.innerHTML.includes('AUD Entitlement Product')) { 
      return cell.innerHTML; 
    } 
})");

```

If you get the appropriate value returned here, then it’s either a bug in the WebUI.executeJavaScript() method, or an error in your usage of it.

---

<div class="post-metadata">

**Author:** ![Brandon\_Hein](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/brandon_hein/32/1092_2.png) [@Brandon\_Hein](https://forum.katalon.com/u/Brandon_Hein)\
**Post date:** [April 23, 2019, 4:41pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/16 "2019-04-23T16:41:59Z")

</div>

If anyone is curious, here’s the WebUI.executeJavaScript() method implementation (which does basically what I’ve done in #2 from my previous post):

```
    @CompileStatic
    public Object executeJavascript(String script, List arguments, FailureHandling flowControl) {
        WebUIKeywordMain.runKeyword({
            WebDriver webDriver = getWebDriver()
            if (!(webDriver instanceof JavascriptExecutor)) {
                throw new StepFailedException(MessageFormat.format(CoreWebuiMessageConstants.KW_MSG_WEBDRIVER_DOES_NOT_SUPPORT_JS, webDriver.getClass().getName()))
            }
            JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver
            Object result = jsExecutor.executeScript(script, arguments != null ? arguments.toArray() : new Object[0])
            logger.logPassed(MessageFormat.format(CoreWebuiMessageConstants.KW_LOG_PASSED_EXECUTE_JS_SUCESSFULLY, script))
            return result
        }, flowControl, true, CoreWebuiMessageConstants.KW_MSG_UNABLE_TO_EXECUTE_JS)
    }
```

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 4:55pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/17 "2019-04-23T16:55:41Z")

</div>

> [@Brandon\_Hein](#):
>
> String test = WebUI.executeJavaScript(“return ‘Hello world!’;”, null);

Valid code. Will return a string value “Hello world!”

> [@Brandon\_Hein](#):
>
> Try executing your JS directly through WebDriver, instead of the WebUI API:

But there’s no point, Brandon. His code does not return a value except `undefined` which is correct for that code when wrapped by Kat/Webdriver and inserted in the page. As I said earlier in the thread:

> [@Russ\_Thomas](#):
>
> Background: When Groovy wraps your JS and passes it to the browser, it is inserted into an anonymous function like this:
> 
> ```auto
> WebUI.executeJavaScript('alert("hey!");', null)
> 
> ```
> 
> // – becomes – //
> 
> ```auto
> function() {
> alert("hey!");
> }();
> 
> ```
> 
> And the result of a function that does not return anything, is `undefined` – which is exactly what that IIFE above would do.

Jeff (and perhaps his developer?) think they can return early from `.forEach`, which, like `.each` in Groovy, means “visit them all” - there is no way to exit early.

---

<div class="post-metadata">

**Author:** ![Brandon\_Hein](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/brandon_hein/32/1092_2.png) [@Brandon\_Hein](https://forum.katalon.com/u/Brandon_Hein)\
**Post date:** [April 23, 2019, 5:06pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/18 "2019-04-23T17:06:52Z")

</div>

> [@Russ\_Thomas](#):
>
> Jeff (and perhaps his developer?) think they can return early from `.forEach` , which, like `.each` in Groovy, means “visit them all” - there is no way to exit early.

I think you’re probably right, just trying to address some unknowns. To your point, could he use a `break;` upon finding the correct element? Thinking something like:

```
var title_cells = document.querySelectorAll(".views-table tbody tr td.views-field-title");
var innerHTML;
title_cells.forEach(function(cell) { 
if (cell.innerHTML.includes("AUD Entitlement Product")) {
    innerHTML = cell.innerHTML;
    break;
} 
})
return innerHTML;

```

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 5:07pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/19 "2019-04-23T17:07:51Z")

</div>

> [@Brandon\_Hein](#):
>
> To your point, could he use a `break;` upon finding the correct element? Thinking something like …

Nope. He needs the methods I showed him earlier:

 ![image](https://europe1.discourse-cdn.com/katalon/original/2X/5/50263f823f4ef95647e9aff81c23dbd521b4e93a.png)

---

<div class="post-metadata">

**Author:** ![Russ\_Thomas](https://dub1.discourse-cdn.com/katalon/user_avatar/forum.katalon.com/russ_thomas/32/11884_2.png) [@Russ\_Thomas](https://forum.katalon.com/u/Russ_Thomas)\
**Post date:** [April 23, 2019, 5:09pm UTC](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611/20 "2019-04-23T17:09:14Z")

</div>

This is probably the oldest/least-fashionable way to go about it…

```auto
  var title_cells = document.querySelectorAll('.views-table tbody tr td.views-field-title'); 
  for(var i = 0; i < title_cells.length; i++) {
    if (title_cells[i].innerHTML.includes('AUD Entitlement Product')) {
      return title_cells[i].nextElementSibling.innerHTML;
      //return title_cells[i].innerHTML;
    }
  }

```

Notice the two `return` statements - not sure which he needs.

But there’s no coverage for a completed loop there. Suggest returning `-999` or something.

[Next page](https://forum.katalon.com/t/variable-not-receiving-value-from-javascript/23611.md?page=2)
