2

I'm working on the LWC that sends an event to Google Tag Manager via window.dataLayer.push().

I have the Lightning Locker service enabled, so I cannot access the window property fully.

I can push to dataLayer via the CustomEvent though:

const pushToDataLayer = new CustomEvent('pushToDataLayer', {
    detail: {
        ...
    },
    bubbles: true,
    composed: true
});
this.dispatchEvent(pushToDataLayer);

It works just fine.

The task that I try to accomplish is to register a callback. The goal is

  • Push an event to dataLayer from the LWC
  • Get the response from Google
  • Do something in the LWC based on that response

Is there a way to achieve that?

Could we send a CustomEvent down to the LWC? Could we invoke Apex from the window (custom JS in the <head> section)? Rest API? EMP API?

I ran out of ideas :( Any help is much appreciated!

1 Answer 1

0

You can achieve this by using Lightning Message Service (https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_message_channel).

connectedCallback() {
    window.addEventListener('message', (event) => {
        const messageContext = createMessageContext();
        publish(messageContext, messageChannel, event.data);
        releaseMessageContext(messageContext);
    });
        
    this.messageChannelSubscription = subscribe(
       this.messageContext,
       messageChannel,
       (message) => this.handleMessage(message));
}
2
  • Hi, thanks for your reply. The last time I had a call with SF, there was a limitation on cross-component usage of LMS inside Communities (LEX). I completely forgot about my question, but as it turns out, you can send CustomEvents back to LWC. It works with enabled Lightning Locker Service. If you have bubbles: true you can listen for the event in child LWC.
    – Frelseren
    Commented Apr 5, 2022 at 18:37
  • Ah, so you wanted to send an event from the parent's window context to the child LWC, right? I thought you meant switching context from window to class within the same LWC component.
    – ziniewiczp
    Commented Apr 6, 2022 at 8:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .