function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
FastSnailFastSnail 

How can I use custom labels in external javascript file?

Custom labels are accessible in JS when script is embedded in page. Below works fine
<apex:page>
<script>
$(document).ready(function(){
alert('{!$Label.myLabel}');   ///Displays 'myLabel content' just fine
});
<script>
</apex:page>
I want to externalize the javascript to an external file:
<apex:page>
<script src="https://www.ccnus.org/various/jquery/jquery-1.11.1.min.js"></script>
<script src="https://www.ccnus.org/........./myexternal.js" ></script>
</apex:page>
Myexternal.js :
$(document).ready(function(){
alert('{!$Label.myLabel}');   ///renders {!$Label.myLabel} rather than myLabel content
});
I have tried everything I could think of. No aval. How do you get it to work?
Thanks in advance for your help,
Jerome
Best Answer chosen by FastSnail
V V Satyanarayana MaddipatiV V Satyanarayana Maddipati
Hi Jerome,

Please follow the below steps:
//Add below 2 lines of code in the visualforce page

window.$Label = window.$Label || {};
$Label.customLabel= '{!($Label.myLabel)}'; // assigning the label to the JS variable.

//Access the above declared variable in your Exteranal Javascript file as shown below.

var x =  $Label.customLabel;
alert(x);
Hope now you are able to access the Custom Label in your Javascript file.

Thanks
Satya.

All Answers

V V Satyanarayana MaddipatiV V Satyanarayana Maddipati
Hi Jerome,

Please follow the below steps:
//Add below 2 lines of code in the visualforce page

window.$Label = window.$Label || {};
$Label.customLabel= '{!($Label.myLabel)}'; // assigning the label to the JS variable.

//Access the above declared variable in your Exteranal Javascript file as shown below.

var x =  $Label.customLabel;
alert(x);
Hope now you are able to access the Custom Label in your Javascript file.

Thanks
Satya.
This was selected as the best answer
FastSnailFastSnail
Thank you for the quick reply Satya. It does work. I just found http://salesforce.stackexchange.com/questions/32746/custom-labels-in-javascript for more info. The problem is that you have to declare everyone of the labels that you need in the 'bridge'. Not practical. Thanks anyway.
Best regards,
Jerome