Cross-domain JavaScript code with sibling sub-domains
Asked Answered
A

2

5

I have two web applications setups:

david.example.com and john.example.com

David opens a new window to John:

window.open('john.example.com');

John would now like to set an input element back on David:

$("#input", window.opener.document).val("Hello David.");

My problem is that this doesn't work on most modern browser because of cross-domain scripting security. I've also tried setting document.domain to different domain combinations both on David and John with no success.

The only time this does work is if John is on example.com and both have document.domain set to example.com. However, example.com is our main website and is not available as a solution.

So is there a way I can do the above example while making the solution works in all modern security conscious browsers?

Notes

  • I control example.com and all its sub domains.
  • David and John are separate web applications and cannot be hosted on the same sub-domain.
Adelinaadelind answered 3/3, 2011 at 16:40 Comment(1)
What do you mean with "However, example.com is our main website and is not available as a solution."? Setting document.domain to "example.com" is the right solution.Amortize
I
8

You should be able to do this, as long as you set document.domain on both DOM's.

document.domain = location.host.replace(/^.*?([^.]+\.[^.]+)$/g,'$1');

Credited to Martin Jespersen

Immesh answered 3/3, 2011 at 16:45 Comment(0)
L
-1

You can always use iframes for cross domain communication and send messages via the hashbangs. See this for an example. It's basically the workings of stuff like Facebook connect. If one app opens the other window I'm guessing you can do that with normal windows as well.

Lanfranc answered 3/3, 2011 at 16:43 Comment(2)
This doesn't work anymore in modern browsers like Chrome and FF4 :(Adelinaadelind
It doesn't? I guess you could use the HTML5 features for it if available in a newer browser (see html5demos.com/postmessage2).Knavish

© 2022 - 2024 — McMap. All rights reserved.