Access Elements of Parent Window from Iframe

Access elements of parent window from iframe

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 

Access parent URL from iframe

You're correct. Subdomains are still considered separate domains when using iframes. It's possible to pass messages using postMessage(...), but other JS APIs are intentionally made inaccessible.

It's also still possible to get the URL depending on the context. See other answers for more details.

How to access iframe window variables from parent window?

So after some more trial and error I've figured it out myself!

For anyone who's interested the issue is that the iframe window hadn't fully loaded by the time my parent function was called, so the variable returned undefined.

The work around was to use a function to check for when the iframe has finished loading before calling the function, for which I found some helpful code on another stack overflow post here:

How to check if iframe is loaded or it has a content?

Select an element in parent Window from Iframe in an onclick event Jquery

It should be done through window.parent, like below:

    var parentItem = window.parent.document.getElementById('elementfromparentwindow'); 

$(parentItem).on('click', function(){

});

Access parent window from iframe (cross-domain)

If I were you I would check out window.postMessage. It may do what you want:

For reference see the following:

  • MDN - Window.postMessage
  • https://stackoverflow.com/a/3076648/296889 - see the Window.postMessage section

Calling a parent window function from an iframe

<a onclick="parent.abc();" href="#" >Call Me </a>

See window.parent

Returns a reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference to itself.

When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window.

How to access iframe into parent window from iframe itself?

Try the following in the script running in the iframe:

var loadeds = top.document.querySelectorAll('.loaded');
for(var i = 0; i < loadeds.length; i++){
var src = loadeds[i].getAttribute('src'),
this_url = document.URL;

if(src === this_url){

console.log('This is running from frame ' + (i + 1) + ' with the src attribute as ' + this_url);

// Alternatively you could use.
// alert('This is running from frame ' + (i + 1) + ' with the src attribute as ' + this_url);
}
}

Didn't get to try it, but if you run this script in an iframe with your HTML structure above, you should get a console message telling you which frame the script is running in.



Related Topics



Leave a reply



Submit