Access iframe elements in JavaScript

2018-12-31 22:59发布

I have a webpage where there is a textarea within an iframe. I need to read the value of this textarea from its child page using JavaScript.

Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

Can anyone please give me any pointers to resolve this issue?

6条回答
几人难应
2楼-- · 2018-12-31 23:06

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

not working for me but I found another solution. Use:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

I checked it on Firefox and Chrome.

查看更多
何处买醉
3楼-- · 2018-12-31 23:07

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');
查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 23:20

Two ways

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 23:22

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 23:24

You should access frames from window and not document

window.frames['myIFrame'].document.getElementById('myIFrameElemId')
查看更多
皆成旧梦
7楼-- · 2018-12-31 23:32

Make sure your iframe is already loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>
查看更多
登录 后发表回答