从具有不同域的iframe内部进行AJAX调用 [英] Making AJAX calls from inside of an iframe with different domain

查看:188
本文介绍了从具有不同域的iframe内部进行AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经尝试了脚本注入,但是它不起作用,因为它不起作用iframe的来源是安全的。
我与加州DMV网站做了一个简单的小提琴 here



我收到DOM异常8错误。这是一个安全问题吗?

解决方案

不可能在具有不同域源的iframe中修改或调用JS调用。出于安全考虑,这在所有浏览器中受到限制。



请参阅同源策略,了解帧间安全性如何工作。简而言之,出于安全原因,不同域之间的帧之间的通信很少。您不能在不同域之间的帧之间进行任何直接的Javascript调用。



有一种方法可以进行跨域ajax调用,它涉及使用 JSONP 。基本上,您将脚本标记注入到自己的框架中,该脚本标记指向Web上任何位置的服务器端点。由于脚本标记的src值不受同一个源策略的限制,因此您可以访问该服务器。但是,现在你需要有一个方法来获得这个结果。这是使用JSONP完成的,您在服务器中指定您要返回的JavaScript调用的JavaScript函数。那返回的javascript可以将JavaScript数据传递给所需的函数。 JSONP需要客户端代码和服务器代码之间的合作,因为正常的ajax调用可能不支持JSONP的额外部分。但是,通过双方的合作,您可以为支持JSONP的服务器端点提供相同的起始策略。



HTML5具有可以安全地传达数据的新消息传递系统(不是直接的JS调用)在不同域中的协作框架之间。请参阅此处 here ,了解HTML5消息传递的工作原理。


Is it possible to do AJAX calls from inside an iframe that has a different domain source?

I've tried script injection but it doesn't work because the iframe's source is secure. I made a simple fiddle with California DMV website here.

I'm getting DOM exception 8 error. Is it a security issue?

解决方案

It is not possible to modify or make JS calls in an iframe with a different domain source. This is restricted in all browsers for security reasons.

See the "Same Origin Policy" for a description of how inter frame security works. In a nutshell, there is very little communication allowed between frames on a different domain for security reasons. You cannot make any direct Javascript calls between frames on different domains.

There is a way to make cross domain ajax calls and it involves using JSONP. Basically, you inject a script tag into your own frame and that script tag points to server endpoint anywhere on the web. Since the src value of a script tag is not restricted by the same origin policy, you can reach that server. But, now you need to have a way to get that result back. That is done using JSONP where you specify in your server request a javascript function that you want the returned javascript to call. That returned javascript can have javascript data in it that is then passed to the desired function. JSONP requires cooperation between both client code and the server code since a normal ajax call might not support the extra part of JSONP. But, with this cooperation of both sides, you can get around the same origin policy for server endpoints that support JSONP.

HTML5 has a new messaging system that can safely communicate data (not direct JS calls) between cooperating frames in different domains. See here and here for a description of how the HTML5 messaging works.

这篇关于从具有不同域的iframe内部进行AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆