如何从iframe中获取元素

时间:2011-04-29 17:51:35

标签: javascript iframe

我想使用JavaScript从iframe中获取元素。我尝试了以下内容:

var iframe = document.getElementById(“iframe id”);

var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;

 iframe.onload = function(){


        alert(iframeWindow.getElementById('notice'));

    };

任何人都可以帮我解决这个问题吗?

跨域

感谢回复

3 个答案:

答案 0 :(得分:3)

假设它全部在同一个域上;

var ifr = document.getElementById('the_iframes_id');
//or window.frames[x].
var doc = ifr.contentDocument || ifr.contentWindow.document;
alert(doc.getElementById('notice'));

如果它不在同一个域中,则出于安全原因,您无法访问它。

答案 1 :(得分:0)

如果你想跨领域这样做,那你就不走运了。 Javascript的安全模型不允许使用它。

我不知道你想要完成什么,但是你可能能够通过服务器端脚本获得你需要的东西。 Perl / PHP / Python / Ruby /任何脚本通常都可以检索您需要的任何网页。然后它可以解析您需要的位并通过AJAX调用将其返回到您的Javascript。

当然这比使用JS更复杂,并假设iframe的内容不是动态的,基于此时的cookie或其他会话内容。

答案 2 :(得分:0)

document.getElementById('iframeResult').contentWindow.document.getElementById('buttonId')

其中 iframeResult 是iframe的ID, buttonId 是元素的ID