当方javascriptの初心者です。
親ページ:A.com
子ページ:B.jp
のiframeがあります。
親から子に値を送信しようと思い、
postMessageをしているのですが、
なかなか子側で受け取りができません。
どのように修正したらいいかご教示いただけませんでしょうか。
(親)
javascript
1 var message = 'hogefuga'; 2 contentWindow.postMessage(message,"https://B.jp");
(子)
javascript
1 window.addEventListener( 2 'message', 3 function(e) { 4 //クロスドメイン用のホストを設定 5 var ta_host = "A.com";//値送信元ホスト指定 6 if (e.origin == 'http://'+ta_host||e.origin == 'https://'+ta_host) { 7 alert('e.data:'+e.data);//hogefuga がアラートされることを期待 8 } 9 });
★追記★
親ページのconsoleには、
Uncaught TypeError: Cannot read property 'postMessage' of undefined
at <anonymous>:1:311
at dispatch (jquery.min.js:3)
at i (jquery.min.js:3)
と出ています。
(jQueryが読まれる前に処理が走ってしまっているからかと思い、
念のため下記の様に修正してみましたが、やはりエラーが生じます。)
親ページ
javascript
1 //jQuery呼び出し前に処理することを避ける。 2if(typeof jQuery == "undifined"){ 3 document.write("script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'><\/script>"); 4} 5//念のためjQueryがあることを確認しつつ実行 6if(typeof jQuery !== "undifined"){ 7 var message = 'hogefuga'; 8 contentWindow.postMessage(message,"https://B.jp"); 9}