GreasemonkeyでクロスドメインiframeのcontentWindowにアクセスするとエラーになる件の回避方法
http://from.example.org/ のページでほげほげした結果を
iframeで開いたhttp://to.example.com/ のページにwindow.postMessageで渡して、
そっちのGreasemonkeyで何か処理をさせるみたいなGreasemonkeyを書いててハマったのでメモ。
こんな感じのコードだったのだが、Firebugのcosoleでなら動くのに
Greasemonkeyの中で動かそうとすると動かなかった。
function executeBid(ids){ var $iframe = $('<iframe/>',{ src:'http://to.example.com/' }); $iframe.bind('load',function(){ this.contentWindow.postMessage(JSON.stringify({command:'hoge',data:ids}),'http://to.example.com/'); }); $iframe.appendTo('body'); }
これによると、
Greasemonkey0.8系の段階では、クロスドメインiframeのcontentWindowにアクセスするとエラーになるというのが原因らしい。
ついでに、0.9系では直っているらしい。
0.8系のままでも動くようにするにはどうすればいいのか?
contentWindowにアクセスするところをGreasemonkeyの外にしてしまえばいい。
function executeBid(ids){ var iframeId = 'iframe-'+Date.now(); var $iframe = $('<iframe/>',{ src:'http://to.example.com/', id:iframeId }); $iframe.bind('load',function(){ location.href='javascript:('+ (function(){ document.getElementById('__iframeId__') .contentWindow.postMessage(JSON.stringify({command:'hoge',data:__ids__}),'http://to.example.com/'); }).toString() .replace('__iframeId__',iframeId) .replace('__ids__',ids.toSource()) +')()'; }); $iframe.appendTo('body'); }