Thursday, December 8, 2022

Use Lightning Web Components in External Website

 


In this blog, we'll look at how to use Lightning Web Components (LWC) on a public website. I'll walk you through each step so you can use it without any problems.

First, develop a Lightning Web Component that will be accessible without requiring a login. Insert the necessary markup into the Lightning Web Component. Here if you see the LWC html we have a property {recId}, we are going to pass this value from the URL. Which we will see in the later steps.

examspagelwc.html

<template>
<lightning-card>
Hi <b> {recId} </b>
</lightning-card>
</template>

examspagelwc.js

import { LightningElement } from 'lwc';

export default class Examspagelwc extends LightningElement {
recId;

connectedCallback() {
const param = 'id';
this.recId = this.getUrlParamValue(window.location.href, param);
}

getUrlParamValue(url, key) {
return new URL(url).searchParams.get(key);
}
}

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

To make it available to the whole public, we must implement the ltng:allowGuestAccess interface.

quizapp.app
<aura:application extends="ltng:outApp" access="global" implements="ltng:allowGuestAccess" >
<aura:dependency resource="c:examspagelwc"/>
</aura:application>
exampagevf.page
<apex:page showHeader="false" sidebar="false">
<apex:includeLightning /> <!--<apex:includeScript value="/lightning/lightning.out.js" />-->

<script>
$Lightning.use("c:quizapp", function() {
$Lightning.createComponent("c:examspagelwc",
{
},"new",
function(cmp) {
console.log('LWC Componenet added in VF page');
});
});
</script>
<div id="new"></div>
</apex:page>

Go to Setup
From Sites and Domains, Select sites
Click on NEW
Give the Site Label
For Active site home page click on lookup and select your VF Page
Then click Save button AND Activate the site.

Now copy the the site url and pass the parameter that we are passing in lwc js to show it in our lwc html.

For example:
if site URL is:- https://2022quizapp-developer-edition.ap26.force.com/

then we need id to pass in the url. so our url look like this:
https://2022quizapp-developer-edition.ap26.force.com/?id=201

So when we open this url, our LWC will show Hi 201



1 comment: