Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only variable expressions returning numbers or booleans are allowed in this context

Tags:

I am trying to pass a value to my javascript function but that function call depends on a boolean variable. I had this working fine until I recently upgraded to thymeleaf security 5.

This is the code snippet.

<body th:onload="${timerEnabled} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'"> 

timerEnabled has to be true for the function call to be done but thymeleaf now throws an exception as

org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler.  

How can I resolve this? Thank you.

like image 403
Knight Rider Avatar asked Oct 22 '18 15:10

Knight Rider


2 Answers

Since Thymeleaf 3.0.10 they fixed a security-bug regarding unescaped code.

Try

<body th:onload="[[${timerEnabled}]] ? 'javascript:runTimer(\'' +  [[${timeRemaining}]] + '\');'"> 

Or the recommended way:

<body th:data1="${timerEnabled}"   th:data2="${timeRemaining}"     th:onload="this.getAttribute('data1') ? javascript:runTimer(this.getAttribute('data2'));"> 

To read more: https://github.com/thymeleaf/thymeleaf/issues/707 And: http://forum.thymeleaf.org/Thymeleaf-3-0-10-JUST-PUBLISHED-tt4031348.html#a4031353

like image 132
leome Avatar answered Sep 18 '22 11:09

leome


I was able to have it working by using this approach

<body>  <script th:inline="javascript">     /*<![CDATA[*/      var flag = [[${timerEnabled}]]; // if timer should be included or not     var timeRemaining = [[${timeRemaining}]]; // the time remaining.     window.onload = function() {         if(!flag)             return; // Exit/Return if the variable is false         runTimer(timeRemaining); // Call your favourite method if the variable is true     };      /*]]>*/ </script> 

Any other approach such as suggested in the exception is appreciated.

like image 28
Knight Rider Avatar answered Sep 21 '22 11:09

Knight Rider