简体   繁体   中英

How can I call a function in an iframe's parent using Greasemonkey

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM