javascript iframe 跨網域執行

這是拿來做筆記用的,在網路上找到iframe的跨網域解決方案

Iframe cross domain JavaScript calls

八月 25, 2009

At ZYB we have been doing cross domain JavaScript calls for quite some time now. Whenever we tell that to people, many don’t believe it is possible with standard security settings in any modern browser. This surprised me a bit since it has always been possible with a simple little trick.

The problem

Say you have a website (site A) with an iframe wherein you host another website (site B). In old and unsecure browsers it was possible to do a JavaScript call from site B to site A like this:

window.parent.doSomething();

Here the doSomething function is living on site A and is called by site B through its parent window. For security reasons, this simple way of cross iframe communication was disabled years ago by all browser vendors.

The solution

There are different scenarios with possible solutions:

1: Site B is a sub domain under/beside Site A

Let’s say that:

  • Site A is located at example.com or sitea.example.com
  • Site B is located at siteb.example.com

All you need to do is to add this line of JavaScript to both site A and B:

document.domain = ‘example.com’

That tells the browser that both site A and B belongs to the app located at example.com and are therefore allowed to communicate using JavaScript. It could be by callingwindow.parent.doSomething(); Now Same Origin Policy principle has been enabled on both sites.

2: Site B is on a different top domain than site A

This is more tricky, because we need to let the browser think both site A and B are under the same top domain.  When it does, we can implement the trick from solution 1 above.

Let’s say that:

  • Site A is located at example.com or sitea.example.com
  • Site B is located at foobar.com

To make this work, you need to create a sub domain called e.g. siteb.example.com. Then point the new sub domain to the IP address of foobar.com. Now both site A and B is located under example.com and you can start to implement solution 1.

There is no security risk going on here because you can only implement solution 1 if both site A and B participate in the trick.

Other solutions

If you can’t use either solution 1 or 2 the game isn’t over. Here are some other techniques to use:

Though not as simple as the document.domain trick, these are well documented and proven techniques.

 

========

原始來源:
http://madskristensen.net/post/Iframe-cross-domain-JavaScript-calls.aspx

Comments are closed.

Close Print