get attribute value of parent element from iframe

2019-07-06 11:37发布

Is there a way to get the value of attribute data-media if I'm running the script inside the iframecontent?

Code looks like this:

<div id="myDiv">
    <iframe data-create-resource-url="http://my.domain.url" 
       data-media="Song" 
       frameborder="0" 
       height="41" 
       src="https://different.domain.url" width="366">
     </iframe>
</div>

I've tried a lot of ways already like window.parent.document or top.document or window.parent and other available solutions but doesn't seem to work.

3条回答
相关推荐>>
2楼-- · 2019-07-06 12:21

Well you dont really need to access the parent. As you are running the script inside iframe. iframe is currently the window for your script inside iframe. So accessing window element should give you the said attr. Try this (not tested):

alert($(window).attr('data-media'));
查看更多
时光不老,我们不散
3楼-- · 2019-07-06 12:33

Did you tried this:

window.frameElement.getAttribute("data-media");
查看更多
神经病院院长
4楼-- · 2019-07-06 12:39

Firstly, add an ID or CLASS to your iframe element (such as id='myframe')
You can then use jquery to access any of the attributes with:

var parent=window.parent.document.getElementById('#myframe');

Now simply get your attribute (not tested):

myAttr=$(parent).data("my-data-attribute") or
myAttr=$(parent).attr("myelement")
查看更多
登录 后发表回答