views:

244

answers:

2

How does the Same Origin Policy apply to the following two domains?

http://server1.MyDomain.com

http://server2.MyDomain.com

Can I run JS on a page hosted on server1, if the content is retreived from server2?

edit according to Daniel's answer below, I can include scripts between different subdomains using the <script> tag, but what about asynchronous requests? What if I download a script from server2 onto the page hosted on server1. Can I use the script to communicate asynchronously with a service on server2?

+4  A: 

You can only include scripts between different subdomains using the <script> tag, as it is exempt from the policy.

Using http://www.example.com/dir/page.html as source (from Wikipedia):

Compared URL                               Outcome  Reason
---------------------------------------------------------------------------------------------
http://www.example.com/dir/page.html       Success  Same protocol and host
http://www.example.com/dir2/other.html     Success  Same protocol and host
http://www.example.com:81/dir2/other.html  Failure  Same protocol and host but different port
https://www.example.com/dir2/other.html    Failure  Different protocol
http://en.example.com/dir2/other.html      Failure  Different host
http://example.com/dir2/other.html         Failure  Different host (exact match required)
http://v2.www.example.com/dir2/other.html  Failure  Different host (exact match required)

UPDATE:

Can I use the script to communicate asynchronously with a service on server2?

Yes, you can with JSONP, which takes advantage of the open policy for <script> tags, to retrieve JSON from other origins.

You may also want to consider using a reverse proxy, as desribed in the following Stack Overflow post:

Daniel Vassallo
@Daniel, thanks for the reply. I've edited the question with a follow up question. Any chance you could add your thoughts to it? Thanks
DaveDev
@Dave: You might want to check out JSONP. You may also want to consider setting up a reverse proxy, as described here: http://stackoverflow.com/questions/2482916/what-am-i-missing-in-the-xmlhttprequest/2482941#2482941
Daniel Vassallo
A: 

Sure, you can run any script that you insert on your never mind where it comes from. Think about how to insert a google map on your page.

What your describe is a pattern called jsonp. Where a server on a other host returns a script you insert in your page and the script calls a function in your page with the response arguments.

eskimoblood