How to call Loaded External JavaScript on click of a Button in Salesforce Lightning Web Component?

How to call Loaded External JavaScript on click of a Button in Salesforce Lightning Web Component?

Sample External JavaScript Code:

window.ExampleJS = ( function() {
    return {
        exampleMethod: function() {
            console.log( 'Inside exampleMethod from External JavaScript' );
        }
    };
}());

Static Resource:

Sample Lightning Web Component Code:

HTML:

<template>
    <lightning-card>
        <lightning-button variant="brand" label="Click"  onclick={callExample}></lightning-button>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';
import Example from '@salesforce/resourceUrl/ExampleJS';
import { loadScript } from 'lightning/platformResourceLoader';

export default class ExternalJavaScript extends LightningElement {    
    
    connectedCallback() {

        loadScript( this, Example )
        .then( () => {
            console.log( 'Script Loaded Successfully' );            
        } )
        .catch( error => {
            console.log( 'Error is', JSON.stringify( error ) );
        } );  
    
    }

    callExample() {

        console.log( 'Inside Call Example' );
        ExampleJS.exampleMethod();

    }

}

JS-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply