[SalesForce] Custom labels in javascript

How one can access custom labels in javascript linked as separate static resource?

For example, some user action on the page should trigger confirmation dialog with custom message. And this message should be translated. Anything else on the page can be translated just fine with custom labels. The problem is that accessing custom labels requires VF context and {!xxx} syntax which of course doesn't work in separate resource.

So, is there a way to access custom labels from javascript? (Or any appropriate way to translate script messages)

Best Answer

This is a great question, and Custom Labels and the $Label global are the right place to start! Instead of evaluating Visualforce inside your JavaScript, you can do a little bit of JavaScript inside your Visualforce.

How do I get evaluated Visualforce variables into dumb static JavaScript?

  1. Load your Custom Labels into the platform using the normal interface,

  2. Create what I like to call a "JavaScript bridging component" that 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>
    
  3. Now in your javascript (in a static resource) use the variables just as if they were VF without {!}

    <script src="{!URLFOR($Resource.ScriptZip, '/my.js')}">
        //NOTE: this example code is for clarity,
        //really he lives in the static resource
        function errorHandler() {
            console.log($Label.MyError);
            alert($Label.MyMessage);
        }
    </script>
    

vf-js-bridging-component

This is in the spirit of the platform: there is no need to interpret any variation on the token names and you can pluck the values straight out in your JavaScript without inventing anything :-)

Related Topic