0

I have scenario like calling a lightning component from VF page. Once value updated in lightning component the parent window(VF page) should get reloaded. I have already come across the Same Question but did not find any answer to it.

1 Answer 1

3

Two important things you need to know about communicating between Lightning Components and Visualforce Pages

  1. Different DOM
  2. Different Origin

When you are calling the lightning component form Visual force page then the both serve different domains. The browser’s same-origin policy prevents a page from accessing content or code in another page loaded from a different origin (protocol + port + host). In this case, Lightning component can't access the VF page directly.

For same, postMessage() can be used to communicate between Lightning Components and Visualforce pages. In your case, we can implement something like below :

To receive the messages in your Visualforce page, you simply set up a listener for message events: VF Page :

$Lightning.use("c:VFLightningApplication", function() {
  $Lightning.createComponent("c:VFLightningComponent", {  }, "lightning", function(cmp) {
        // do some stuff
  });
});

var vfOrigin = "yourdomain-dev-ed--c.na35.visual.force.com";
window.addEventListener("message", function(event) {
    if (event.origin !== vfOrigin) {
        // Not the expected origin: Reject the message!
        return;
    }
    // Handle the message
    if(event && event.data) {
    // Validate the message content and reload the page
      if(event.data === 'updateValue') {
        location.href = location.href;
      }           
    }
}, false);
  • vfOrigin is the origin (protocol + port + host) Visualforce pages are loaded from. This is where we expect the messages to come from.
  • event.origin is the actual origin of the window that sent the message at the time postMessage() was called. You should always verify that the actual origin and the expected origin match and reject the message if they don’t.
  • event.data is the message sent from the other window (To send multiple parameters to create JSON object and stringify it as string).

Lightning Component :

const vfHostUrl = "yourdomain-dev-ed--c.na35.visual.force.com";
const message = 'updateValue';
parent.postMessage(message, vfHostUrl);
  • The message field is used to capture the simple string message we will send to the Lightning Component.
  • The second argument of postMessage() is the origin of the parent window. Again, the event will not be sent if the content of the parent window at the time postMessage() is called wasn’t loaded from lexOrigin.

Please refer this link for more details. Great article to understand the Communicating between Lightning Components and Visualforce Pages

You must log in to answer this question.

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