Using window.postMessage(message, uri) in Greasemonkey?

320 views
Skip to first unread message

slickplaid

unread,
Oct 28, 2009, 8:46:28 PM10/28/09
to greasemonkey-users
I'm attempting to write a greasemonkey script that brings up a
messaging window in an iframe that is on a different domain. To send
the information to that iframe from the parent window, I'm trying to
use the postMessage() function, but for some reason I can't get it to
send and/or receive to and from the iframe.

In the greasemonkey script I create a new iframe (I'm using jquery):

$('body').append('<iframe src="http://mysite.com/api.php" id="com"></
iframe>');

In the api.php, I have:

window.addEventListener('message', function(e){
document.getElementById('test').textContent = e.domain+' said:
'+e.data;
}, false);

Now, further down in the greasemonkey script I try and send a simple
message:

window.parent.frames[0].postMessage('hello world', 'http://
mysite.com');

It doesn't register and it doesn't throw any errors to let me know why
it isn't sending. I type the above javascript into FireBug and it
displays perfectly in the iframe and registers that it was sent. Why
doesn't this work the same in Greasemonkey? Is there a work-around or
am I calling the window improperly from the chrome or where ever
greasemonkey is relative to the iframe?

I'm really at a loss to exactly why it won't work. Any help would be
appreciated!

Thanks,
slickplaid

slickplaid

unread,
Oct 31, 2009, 11:48:46 AM10/31/09
to greasemonkey-users
Has anyone ever tried using postMessage() in a greasemonkey script
before that could suggest anything or give an example on how it was
used properly with greasemonkey? I know how to use it properly outside
of greasemonkey but for some reason it won't in a greasemonkey script.

Any response would be helpful!
Thanks,
slickplaid

esquifit

unread,
Nov 15, 2009, 10:31:45 AM11/15/09
to greasemon...@googlegroups.com
There is a script "Songkick Bootleg Injector" by author
deathwarmedover at userscripts.org, sie [1] and [2].

The logic goes along these lines:

The first script [1] runs at domain A. If it detect specific links
pointing to domain B, it opens a popup window with the document from
domain B. The second script [2] runs in the pop up window: it calls a
function defined in the document which generates a HTML snippet. It
then fetches the generated snippet code and sends it back to the
opening window via 'postMessage'. The first window at domain A then
embeds the HTML code in its own document and closes the popup window
at domain B.

I slightly modified both scripts to use an iframe instead of a popup
window. It works as long as you use unsafeWindow when calling
postMessage: unsafeWindow.parent.postMessage.

I suggest you try

unsafeWindow.parent.frames[0].postMessage('...')


[1] http://userscripts.org/scripts/show/60820
[2] http://userscripts.org/scripts/show/60821
Reply all
Reply to author
Forward
0 new messages