在没有服务器端脚本的javascript中使用同源策略 [英] Getting around same origin policy in javascript without server side scripts

查看:188
本文介绍了在没有服务器端脚本的javascript中使用同源策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个环境,不允许服务器端脚本真的(很难得到一个脚本安装在服务器上)。我试图使用iframe违反javascript的同一起源poilcy;然而,这没有工作。是否有其他解决方法,我不知道?



谢谢!

解决方案

如(查看源代码)。



尽管JavaScript的同源策略限制一个域上的代码访问另一个域上的代码,但是如果域彼此嵌套(域A,嵌套在域B中,嵌套在域A中)则无关紧要。



简而言之,内容页面通过xdcomm页面将消息发送到父页面,方法是将iframe的源更改为 http:// domaina.com/xdcomm.html?src=foo&args=[1,2,3,4] 。这相当于在父页面中执行 foo(1,2,3,4)



此外,已知有可以帮助您的库,例如 easyxdm 。我在这里解释的是他们使用的技术之一的基础,虽然它可能不是那么奇怪,它是一个完全正常和轻量级的实现。


I have an environment that doesn't allow server side scripting really (it is extremely difficult to get a script "installed" on the server). I tried using an iframe to violate javascript's same origin poilcy; however, that didn't work. Are there any other workarounds I am not aware of?

Thanks!

解决方案

As David Dorward mentioned, JSON-P is the simplest and fastest; however, there is another trick, specifically using two iframes.

Two get around this issue without using JSONP, you can do the following. This technique assumes that you have some sort of development access to the parent page.

There are three pages on two domains/sites.

  1. Parent page
  2. Content page
  3. Cross-domain communication page (aka "xdcomm")

Pages the parent and xdcomm pages are hosted on the same domain, the content page is hosted on any other domain. The content page is embedded as an iframe in the parent page and the xdcomm page is embedded as a hidden iframe in the content page.

The xdcomm page contains a very simple script that detects GET parameters in the query string, parses that string for method and args variables (where args is a JSON encoded string), and then executes the specified method with the specified arguments in the parent page. An example can be seen here (view source).

Even though JavaScript's Same Origin Policy restricts code on one domain from accessing that of another, it doesn't matter if domains are nested within each other (domain A, nested within domain B, nested within domain A).

So, in a nutshell, the content page sends messages to the parent page via the xdcomm page by changing the source of the iframe to something like http://domaina.com/xdcomm.html?src=foo&args=[1,2,3,4]. This would be equivalent to executing foo(1,2,3,4) in the parent page.

Also, know that there are already libraries that help you with this, such as easyxdm. What I've explained here is the basis of one of the techniques that they use, and while it might not be as fancy, it is certainly a fully functioning and lightweight implementation.

这篇关于在没有服务器端脚本的javascript中使用同源策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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