1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | <!DOCTYPE html> <html lang="zh-TW"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> <style> div { border: solid 2px #336699; margin: 10px; padding: 5px; border-radius: 5px; vertical-align: top; text-align: center; display: inline-block; } .container { background: #88BBFF; width: 520px; } .msg { background: #99CCFF; border: dotted 1px #4477AA; width: 480px; margin: 0px; text-align: left; font-size: 12px; } </style> <script> function init() { var form = document.getElementById('form1'); var input = document.getElementById('input'); var target = document.getElementById('target'); var channel1 = new MessageChannel(); var channel2 = null; setTimeout(function(){ try { target.contentWindow.postMessage('hello', 'http://localhost', [channel1.port2]); }catch(e){alert(e);} }, 500); channel1.port1.start(); form.onsubmit = function(){ try { if(!channel2) { channel2 = new MessageChannel(); channel2.port1.start(); channel2.port1.addEventListener('message', function(e) { var str = '<li>'; str += '[' + e.origin + ']'; str += '[' + e.ports + ']'; str += ' : '; str += e.data; str += '</li>\n'; document.getElementById('msg2').innerHTML += str; }, false); channel1.port1.postMessage(input.value, [channel2.port2]); } else { channel1.port1.postMessage(input.value); channel2.port1.postMessage(input.value); } } catch(e) { alert('submit: '+e); } finally { input.value = ''; input.focus(); return false; } }; channel1.port1.addEventListener('message', function(e) { var str = '<li>'; str += '[' + e.origin + ']'; str += '[' + e.ports + ']'; str += ' : '; str += e.data; str += '</li>\n'; document.getElementById('msg1').innerHTML += str; }, false); } </script> </head> <body> <div><div class="container"><form id="form1"><input type="text" size="30" id="input"></form></div><br> <div class="container">Returned Messages.<div id="msg1" class="msg"></div><div id="msg2" class="msg"></div></div></div> <iframe src="http://localhost/test632a.html" id="target" width="520" height="600" scrolling="no" frameborder="1"></iframe> </body> </html> <script> init(); </script> |
Direct link: https://paste.plurk.com/show/323246