How to pass variable from velocity to javascript?

confluence-server

#1

I want to use the variable from the velocity file inside the javascript file.
(file.vm)

<html>
<head>
<title>red</title>
<meta name=“ajs-context-path” content="/confluence">
$webResourceManager.requireResourcesForContext(“com.acme.plugin.fancy-context”)
</head>
<body>
#set($delay = $delayVal)
#set($link = $url)
<div>redirecting</div>
</body>
</html>

(file.js)

AJS.toInit(function() {
myVar = setTimeout(function(){ location.replace("$link") }, 1000 * $delay);
});

so in this file.js I want to pass the delay and link value to the setTimout function. But it’s not working.

Please help!


#2

You might use a hidden field with the value

<body>
<input type="hidden" name="delay" class="delay" value="$!{delayVal}"/>
<input type="hidden" name="link" class="link" value="$!{url}"/>
<div>redirecting</div>
</body>

With this JS

AJS.toInit(function() {
var delay = AJS.$(".delay").val(); // maybe "delay" is a too general name, use a more specific one
var link = AJS.$(".link").val(); // maybe "link" is a too general name, use a more specific one
myVar = setTimeout(function(){ location.replace("link") }, 1000 * delay);
});

#3

Thank @ppasler, i will try this. I also found this https://developer.atlassian.com/server/confluence/including-javascript-and-css-resources/