HTML5 data-attributes in iframe element
Asked Answered
C

1

9

Can custom data-attributes set on an iframe be accessed by the iframe's content?

Example:

<iframe src="foo.html" data-something="123"></iframe>

Is there a way to access data-something's value form the iframe's document?

Thanks.

Consolute answered 26/11, 2012 at 18:16 Comment(0)
G
17

Yes, use the frameElement attribute.

window.frameElement.getAttribute('data-something');

Demo: http://jsfiddle.net/Ehj2Q/

Of course this does not work at all if the iframe's content are from a different origin.

Grayling answered 26/11, 2012 at 22:42 Comment(2)
This is great, but yeah, not the same domain. I guess the iframe's document can't read it's parent tag's attributes at all then.Consolute
That's right. The only thing that both can access is the src, which is reflected in the frame content's location. So the parent frame can send data using the hash foo.html#something=123, like Closure does. For modern browsers, there's postMessage. But again, this is only possible if the parent frame opts in.Grayling

© 2022 - 2024 — McMap. All rights reserved.