html code

Distribute JavaScript Code within a Lightning Web Component for Accessing URL Parameters

In this article, we’ll craft a Lightning Web Component intended for sharing as a JavaScript library among other LWCs.

We’ll create an LWC Component serving as a utility method for extracting query parameters, demonstrated below:

//Method to read parameter from query string
export function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search); 
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>false</isExposed>  
</LightningComponentBundle>


As observed in the code above, all that’s required is the creation of a JavaScript file and a metadata file for the LWC to function as a JavaScript library. Notice how the function is defined using the ‘export’ keyword. Multiple export methods can exist within the same LWC, serving as a library in your project.

To utilize the aforementioned method in any LWC component, follow the syntax below:

<template> 
  ... Some UI related code here
</template>
import { LightningElement , track } from 'lwc'; 
//Importing reusable LWC Component as Javascript utility
import {getUrlParameter } from 'c/JSUtility';

export default class DemoWrapperLWC extends LightningElement {
   //Some track variables define 
   //...... 
   //.. Some code
  
    //Similar to init method in Aura
    connectedCallback() { 
      //Note - We are NOT using "this" keyword to access method getUrlParameter
      let param1 = getUrlParameter('param1'); 
      console.log('Found Parameter value for param1'+param1);
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
  
</LightningComponentBundle>