javascript 从 iframe 获取文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13038742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:42:05  来源:igfitidea点击:

Get Text from iframe

javascriptdomiframe

提问by Rhs

I have the following HTML

我有以下 HTML

<iframe id ="myIframe">
     #document
         <head>...</head>
        <body>Text I want to get is here</body>
</iframe>

I only know the iframe's id. Using JavaScript, how can I extract the text from the body?

我只知道 iframe 的 id。使用 JavaScript,如何从正文中提取文本?

回答by Majid Laissi

Assuming your iframe is in the same domain as your HTML:

假设您的 iframe 与您的 HTML 在同一个域中:

var myIFrame = document.getElementById("myIframe");
var content = myIFrame.contentWindow.document.body.innerHTML;

Otherwise you'll face some Same Origin Policyissues.

否则,您将面临一些同源策略问题。