Start a new topic
Answered

Receive iframe messages without using old v1 library

I just want to embed an iframe and listen for messages myself ("onResize", "onSubmit", "onSuccess", "onCancel", "onError", ...)


I don't want to pull this: https://js.chargebee.com/v1/chargebee.js It contains old code I don't use.


How come if I don't use this library the embedded iframe doesn't post messages to the parent?


Thank you!


Best Answer

Hello Mike


You can certainly listen to the messages without the library. 


Please check this sample code snippet that listens to the messages sent from the iframe.

 

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  // e.data will be json string
  var messObj = JSON.parse(e.data);
  if(messObj.onload){
    // onload callback
  }
  // |||ly check for

  // messObj.resize
  // messObj.onSubmit
  // messObj.success
  // messObj.cancel
},false);

 


Answer

Hello Mike


You can certainly listen to the messages without the library. 


Please check this sample code snippet that listens to the messages sent from the iframe.

 

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  // e.data will be json string
  var messObj = JSON.parse(e.data);
  if(messObj.onload){
    // onload callback
  }
  // |||ly check for

  // messObj.resize
  // messObj.onSubmit
  // messObj.success
  // messObj.cancel
},false);

 

I was doing that but still it wasn't working.


After re-reading the original library, when embedding the iframe, one must specify the URL of the container like:


<iframe src="<url-of-form>#<url-of-this-page>"/>


Thanks Vaishnavi :)



Login or Signup to post a comment