views:

1415

answers:

1

I have a Greasemonkey script which adds an iframe to the page (call it Page 1). The iframe contains another page (call it Page 2). The script runs on Page 2 as well. Pages 1 and 2 are on different domains.

I'd like to allow code running in Page 2 to call a function on Page 1. Given the lower restrictions on Greasemonkey code, is this possible?

+1  A: 

The browser will prevent this, because the domains are different.

There are a couple of tricks you can use to communicate between frames:

  1. Add a DNS record for the other website to the outer website's domain (www.somewebsite.com and someapp.somewebsite.com). Then use document.domain = "somewebsite.com" in both pages' JavaScript.
  2. Use HTML 5 postMessage() to communicate between frames. I know it works in Firefox 3 and Internet Explorer 8, but not in IE7.
  3. You can pass simple messages to another page by setting the parent window's URL. Note: It appears browsers prevent setting of the parent URL. This method will this only work for one-way communication from parent to child frame.

Ad 3: You won't be able to read the other frame's URL, but you can set it. If you change the URL to the exact same page, but with an #anchor component to the URL, the page will not actually reload:

window.frames["childFrame"].location.href = "http://www.somewebsite.com/#message"

You'd then need to add a script to the outer page that regularly polls it's location.href and process the messages. Yes, it's ugly, but if done right, it will work in all common browsers.

Thorarin
Ooh, postMessage() will do nicely. My idea was to exploit the privileges granted to Greasemonkey scripts to get around the same-domain restriction. This is better; postMessage() is actually intended for this. :)
Peeja
I now have to support IE7, so I've given up on postMessage(). I can't do #1 either. #3 I could do, but I can't get it to work. In FF3 at least, I don't have permission to set window.parent.location.href, even to the parent's current URL. Am I missing something?
Peeja
Hmm, I've only used this method to communicate from the parent frame to the embedded frame, not the other way around. Likely there is some limitation on that to prevent frames from breaking out and forcing themselves to be the top page.
Thorarin
Strangely, I can set the hash on the top window, but not on the iframe's parent, which itself is an iframe in the top window. I've made this a new question:http://stackoverflow.com/questions/999010/why-cant-an-iframe-set-its-parents-location-hash
Peeja