Activity › Forums › Salesforce® Discussions › How can we access custom labels in javascript linked as separate static resource in Salesforce?

  • Kumar

    Member
    February 10, 2017 at 11:33 AM

    Hi Mohit,

    Custom Labels and the $Label global can be used for this purpose! Instead of evaluating Visualforce inside your JavaScript, you can do a little bit of JavaScript inside your Visualforce.

    Load your Custom Labels into the platform using the normal interface,
    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>

    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>

    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.

    Hope this helps.

    • This reply was modified 9 years, 8 months ago by  Kumar.

Log In to reply.

Popular Salesforce Blogs

Top Salesforce Career Paths to Watch in 2026

Blog in

The Salesforce ecosystem continues to evolve rapidly, driven by advancements in AI, automation, data intelligence, and industry-specific cloud solutions. As businesses increasingly rely on Salesforce…

Popular Salesforce Videos