Custom labels in javascript

We can use '{!$Label.Label_Name}' in JS function if this funtion is written on Visual force to access labels.

But Its tricky, If we need to access labels in JS file which is saved in static resource:
There are two way to do the same requiremnt:

1. Pass label as a parameter or pass-through attributes to JS function.

2. JavaScript bridging component:

2.a) loads before your script, like so:
<script>
    window.$Label = window.$Label || {};
    $Label.MyError = '{!JSENCODE($Label.MyError)}';
    $Label.MyPrompt = '{!JSENCODE($Label.MyPrompt)}';
    $Label.MyMessage = '{!JSENCODE($Label.MyMessage)}';
</script>
2.b) Now in your javascript (in a static resource) use the variables just as 
if they were VF without {!}
function errorHandler() {
    console.log($Label.MyError);
    alert($Label.MyMessage);
}

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. Custom food labels

    ReplyDelete