I’ve got a page that contains an iframe. Both the page and iframe reside on the same domain.
Within the iframe there is an AJAX call being made for some data that populates some input fields within the iframe.
I need to extract a variable value called useableData from the iframe back to the parent page. This variable value is one that gets created after the AJAX call.
I find myself stuck at this point. I’ve tried putting an onload function call against the iframe and my variable comes back as undefined.
Attempt #1
$(window).load(function () {
var fName = $("#one-time-form")[0].contentWindow.useableData;
console.log(fName);
});
Realizing that didn’t work I put an onload directly on the iframe element and then re-worked the function
Attempt #2
<iframe id="one-time-form" onload="testFunction();"></iframe>
function testFunction {
var fName = $("#one-time-form")[0].contentWindow.useableData;
console.log(fName);
}
Still nothing they both return an undefined variable value.
Then I came across the .ajaxStop
function in jQuery and gave it a try.
Attempt #3
$(document).ajaxStop(function() {
var fName = $("#one-time-form")[0].contentWindow.useableData;
console.log(fName);
});
This also returned an undefined value, presumably because it’s being called in the parent page where no Ajax calls originated to begin with.
Lastly, I attempted a local storage attempt using the HTML API. I defined the variable within the iframe inside my AJAX success function.
Setting local storage in iframe
localStorage.setItem('fName', useableData);
Then back in the parent page within an onload function call I have this
Retrieve locale storage in parent page
const sessData = localStorage.getItem('fName');
console.log ("session var called sessData is: " + sessData);
But, yet again, I get an undefined variable, presumably because the AJAX call isn’t finished yet.
2
Answers
In general, in order to communicate with an iframe, it’s (usually) necessary to use
postMessage
to send and recieve data, a simple example that you can adopt:and then the source for "something" url..
now back in the main file… (continued)
If you have control of the code in both the iframe and parent window, I’d suggest using
postMessage()