user4759415
user4759415

Reputation:

access value of variable from iframe at the parent level

I've read countless answers to similar questions but I'm just not getting the result I need.

For background... I've got an iframe embedded into my page. Both the parent and iframe are on the same domain. I have some variables within the iframe that I'd like to have access to within the parent page.

The html on the parent page that serves the iframe is like this;

HTML

<iframe id="one-time-form" width="100%" height="1850px" src="https://www.domain-that-parent-and-iframe-reside-on.com/page-url-for-iframe"></iframe>

Within that iframe src is a variable that stores an array of data. This variable is called var useableData

I know that my iframe is loading later than the parent page so I've got my attempt at calling this variable housed within a jQuery function that runs once the whole window is finished loading.

jQuery

$(window).load(function () {
   var fName = $("#one-time-form").contentWindow.useableData;
   console.log(fName);
});

This just returns a console error of Uncaught TypeError: Cannot read property 'useableData' of undefined

Any ideas for why this isn't working or modifications to my approach I should take?

UPDATE

Have tried implementing a postMessage() but it's not co-operating either. I've based it off of this demo: https://usefulangle.com/post/4/javascript-communication-parent-child-window

In the child page I've got this running:

Child Message

  //Function to send data back to the parent window
  function ProcessChildMessage(message) {
     var testMessage = useableData;
  }

Then in the parent page I'm calling this function

Parent Message

window.opener.ProcessChildMessage('Message to the parent');

Still not having any luck with this and am seeing this console error "Uncaught TypeError: Cannot read property 'ProcessChildMessage' of null"

Upvotes: 1

Views: 702

Answers (2)

Barmar
Barmar

Reputation: 780724

You're running this when the main window has loaded, you need to wait for the iframe to be loaded.

And as mentioned in another answer, contentWindow is a DOM property, not a jQuery property, so you need to access the iframe DOM element directly.

$(document).ready(function() {
    $("#one-time-form").on("load", function() {
        var fName = document.getElementById("one-time-form").contentWindow.useableData;
        console.log(fName);
    });
});

Upvotes: 0

Mitya
Mitya

Reputation: 34556

contentWindow is a property of a native window; you're trying to call it on a jQuery object.

Change

$("#one-time-form").contentWindow.useableData;

to

$("#one-time-form")[0].contentWindow.useableData;

Upvotes: 1

Related Questions