如何从 iframe 中获取元素
我想使用 JavaScript 从 iframe 获取元素。我尝试过以下操作:
var iframe = document.getElementById("iframe id");
var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;
iframe.onload = function(){
alert(iframeWindow.getElementById('notice'));
};
谁能帮我让它工作吗?
跨域
感谢回复
I want to get an element from an iframe using JavaScript. I've tried the following:
var iframe = document.getElementById("iframe id");
var iframeWindow = iframe.contentWindow || iframe.contentDocument.parentWindow;
iframe.onload = function(){
alert(iframeWindow.getElementById('notice'));
};
Can anyone help me get this working?
with cross domain
thanks for reply
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设它们都在同一个域上;
如果它不在同一域中,出于安全原因您将无法访问它。
Assuming its all on the same domain;
If its not on the same domain, you cannot access it for security reasons.
如果您想跨域执行此操作,那么您就不走运了。 Javascript 的安全模型不允许这样做。
我不知道您想要完成什么,但您也许可以通过服务器端脚本获得您需要的东西。 Perl/PHP/Python/Ruby/任何脚本通常都可以检索您需要的任何网页。然后它可以解析出您需要的部分,并通过 AJAX 调用将其返回到您的 Javascript。
当然,这比仅仅使用 JS 更复杂,并且假设 iframe 的内容不是动态的,此时基于 cookie 或其他会话事物。
You are out of luck if you want to do this across domains. Javascript's security model will not allow it.
I don't know what you are trying to accomplish, but you might be able to get what you need with server-side scripting. A Perl/PHP/Python/Ruby/whatever script generally has the possibility of retrieving any web page you'd need. It could then parse out the bit you need and return this to your Javascript via AJAX calls.
Of course this is more complicated than just using JS, and assumes that the iframe's content is not dynamic, based on cookies or other session things at this moment.
其中 iframeResult 是 iframe 的 Id,buttonId 是元素的 Id
where iframeResult is Id of iframe and buttonId is Id of element