How to pass variable from velocity to javascript?

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!

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);
});
1 Like

Thank @ppasler, i will try this. I also found this Including Javascript and CSS resources

One could use meta tags as well no ?

<meta name="my-delay" content="$!{delayVal}">

and then

document.querySelector('meta[name="my-delay']).content