3

In order to communicate between an LWC and a Visualforce iFrame I intend to use postMessage.

For example, in VF I might have:

// Function to send a message to the LWC
const sendEventToLWC = function(actionName, details) {
    if ( parent )
    {
        parent.postMessage(
            JSON.stringify({ action: actionName, details: details }),
            lightningOrigin
        );
     }
}

// Listener to respond to post messages from the LWC
window.addEventListener('message', function (event) {
    if (event.origin === lightningOrigin) {
        // Perform the requested action
    }
});

In the LWC I would have very similar code, referencing visualforceOrigin instead of lightningOrigin

The questions are:

  • How do I programatically work out the visualforceOrigin when in the LWC (or Apex) context?
  • How do I programatically work out the lightningOrigin when in the Visualforce (or Apex) context?

1 Answer 1

5

The DomainCreator class (added in the Spring 22 release) does this.

https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_domain_classes.htm&type=5&release=236

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_DomainCreator.htm#apex_System_DomainCreator_getVisualforceHostname

String vfHostname = DomainCreator.getVisualforceHostname(null);
String myLightningHostname = DomainCreator.getLightningHostname();

Hope this helps.

1
  • One note to add, the parameter for getVisualforceHostname is the namespace that you want the hostname for. If the namespace you pass has an underscore in it, the resulting URL is incorrect. That is, the actual URL has the underscore replaced with a dash, the return from DomainCreator.getVisualforceHostname retains the underscore. Nov 16, 2022 at 15:45

You must log in to answer this question.

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