I am communicating betweeen Lightning component and VF page used as iframe inside lightning component. The reference for this is here:
The problem I am facing is that in doInit() of lightningComponent I am using component.find() to find another component using aura:id of that component. But this is getting failed and I get undefined as a result of component.find(). The strange part here is that the eventListner listens to event multiple times. The number of times it listens to event is equal to number of times lightning component is initiated. (i.e no. of time doInit() is executed). I think this is due to phenomenon explained here:
https://triangle717.wordpress.com/2015/12/14/js-avoid-duplicate-listeners/
However, my concern is that why does it not find the component 1st time itself?
Lightning component:
<!-- some code -->
<c:ComponentToBeReferenced aura:id="sampleId" />
:
:<!-- some code -->
:
<iframe aura:id="vfFrame" src="{!v.frameSrc}" width="{!v.frameWidth}" height="{!v.frameHeight}" class="vfFrame" frameBorder="0"/>
:
:
<!-- some code -->
lightning component controller:
doInit : function(component, event, helper) {
helper.otherHelperMethod(component, event, helper);
//Add message listener
window.addEventListener("message", function(event) {
if(event.data.state == 'objectProcessed'){
var comp = component.find('sampleId'); // return undefined
comp.sampleMethod(); // throws error here
}
});
},
VF page script that throws event :
var lexOrigin = 'https://{!$CurrentPage.parameters.lcHost}';
sendToLC({'state':'objectProcessed', 'vfHost': "{!LEFT($CurrentPage.URL,FIND('/',$CurrentPage.URL,9))}"});
//Send message to LC
function sendToLC(message) {
if(typeof(lexOrigin) !== 'undefined'){
parent.postMessage(message, lexOrigin);
}
}
Note: The event is getting thrown only once from VF Page.
Note: I tried moving the code to afterRenderer without any success.
component
also undefined? also - you have 2event
attributes - try renaming one of themundefined
. Also, renaming did not work. I think I found the reason, added that as answer.