[SalesForce] Define a global variable in lightning controller to make it accessible by Java Script which is loaded from the Static Resource

It is possible when we are defining a variable in JS file which will be loaded from static resource and want to use that variable in the Lightning controller as shown in this answer.

I want to do exactly vice versa from the above situation. See explanation below –

  • I will define a variable in Lightning controller and I want to access this variable in the JS file which is loaded from the static resource.

Please give your thoughts. Thanks in advance.

Best Answer

Oh Yes! I got the solution which is mentioned below.

Before the loading of the JS file(which will use that variable) from static resource invoke the function of your lightning controller and write below statement in that function -

initializeVariables : function() {

     window.<VARIABLE_NAME> = 'ANY_VALUE';
}

Surely you will be able to access that variable in your JS file.

Note - Be sure to get your variable initialized before the loading of JS file that will use that variable. Thanks!