Return variable from javascript into a KM variable

I'm trying to pass a variable from the browser into a KM variable. I've looked at the wiki post to execute JavaScript, but I can't get it to pass the data back to KM.

In the above javascript snippet the browser's console shows that I found the right content. But when I uncomment the return statement Chrome throws an error: Uncaught SyntaxError: Illegal return statement. The text in the window just shows "", indicating that it didn't work.

Any idea what I'm doing wrong? Thank in advance.

Just put the value you want to return on the last line of the script. Like this:


I know that's not intuitive, and it took me a while to figure it out. But that's apparently the way it works.

Another way is to use IIFE (Immediately Invoked Function Expression) [IIFE - MDN Web Docs Glossary: Definitions of Web-related terms | MDN] if one find "return" is easier to read.

(function()  {
   // ....
  return "result"


(() => {
    // ....
    return "result";
1 Like

JavaScript's return is only defined inside a function.

( When you just have a sequence of expressions, outside a function context, the last one evaluated is the value you are left with : -)

1 Like