0

There are many lightning components are embedded in a Visualforce page. I've setup many global variables and JS functions to share the state with lightning components. However, it seems no way that a lightning component could access any global variable or JS method from it's parent contaniner(VF page)

1 Answer 1

1

This Communicating between Lightning Components and Visualforce Pages article that you may have seen explains:

Different Origins. Visualforce pages and Lightning Components are served from different domains. For example, if you are using a developer edition:

  • Lightning Components are loaded from a domain that looks like this: yourdomain-dev-ed.lightning.force.com
  • Visualforce pages are loaded from a domain that looks like this: yourdomain-dev-ed–c.na35.visual.force.com

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 our case, that means that a Visualforce page can’t use the parent window reference to access content or execute code in the Lightning Component wrapper. Similarly, the Lightning component can’t use the iframe’s contentWindow reference to access content or execute code in the Visualforce page it wraps.

These restrictions are enforced for very good reasons. But fortunately, there is also an API (otherWindow.postMessage()) that provides a secure approach (when used properly) to exchange messages between different window objects with content loaded from different origins.

So best to think of these as two separate environments and to not attempt to build much logic that spans both.

However, when you have to, you can pass complex objects between the two via the postMessage mechanism where the message can be:

Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.

4
  • Hi @Keith However, the case I have is to have a Visualforce page as the parent container which will dynamically create lightning components. Our customers will direct access the vfp. I didn't see any iframe for the included lightning apps in the vfp. Will that still face the same origin issue?
    – newBike
    Jul 26, 2018 at 18:04
  • @newBike I'm not too clear about your mention of iframe here, but FYI lightning:container "provides the message() method".
    – Keith C
    Jul 26, 2018 at 18:26
  • So far. It seems to me each Salesforce Lightning component is working in a sanitized sandbox. there's no way to access any JS function or variable outside from the component itself.
    – newBike
    Jul 26, 2018 at 21:49
  • @newBike Yes it is a very tied-down environment. Also see Sharing JavaScript Code Across Components.
    – Keith C
    Jul 27, 2018 at 7:49

You must log in to answer this question.

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