worker_messageChannel.js (2373B)
1 function ok(a, msg) { 2 postMessage({ type: "check", check: !!a, message: msg }); 3 } 4 5 function is(a, b, msg) { 6 ok(a === b, msg); 7 } 8 9 function info(msg) { 10 postMessage({ type: "info", message: msg }); 11 } 12 13 function finish() { 14 postMessage({ type: "finish" }); 15 } 16 17 function basic() { 18 var a = new MessageChannel(); 19 ok(a, "MessageChannel created"); 20 21 var port1 = a.port1; 22 ok(port1, "MessageChannel.port1 exists"); 23 is(port1, a.port1, "MessageChannel.port1 is port1"); 24 25 var port2 = a.port2; 26 ok(port2, "MessageChannel.port1 exists"); 27 is(port2, a.port2, "MessageChannel.port2 is port2"); 28 29 ["postMessage", "start", "close"].forEach(function (e) { 30 ok(e in port1, "MessagePort1." + e + " exists"); 31 ok(e in port2, "MessagePort2." + e + " exists"); 32 }); 33 34 runTests(); 35 } 36 37 function sendMessages() { 38 var a = new MessageChannel(); 39 ok(a, "MessageChannel created"); 40 41 a.port1.postMessage("Hello world!"); 42 a.port1.onmessage = function (e) { 43 is(e.data, "Hello world!", "The message is back!"); 44 runTests(); 45 }; 46 47 a.port2.onmessage = function (e) { 48 a.port2.postMessage(e.data); 49 }; 50 } 51 52 function transferPort() { 53 var a = new MessageChannel(); 54 ok(a, "MessageChannel created"); 55 56 a.port1.postMessage("Hello world!"); 57 a.port1.onmessage = function (e) { 58 is(e.data, "Hello world!", "The message is back!"); 59 runTests(); 60 }; 61 62 postMessage({ type: "port" }, [a.port2]); 63 } 64 65 function transferPort2() { 66 onmessage = function (evt) { 67 is(evt.ports.length, 1, "A port has been received by the worker"); 68 evt.ports[0].onmessage = function (e) { 69 is(e.data, 42, "Data is 42!"); 70 runTests(); 71 }; 72 }; 73 74 postMessage({ type: "newport" }); 75 } 76 77 var tests = [basic, sendMessages, transferPort, transferPort2]; 78 79 function runTests() { 80 if (!tests.length) { 81 finish(); 82 return; 83 } 84 85 var t = tests.shift(); 86 t(); 87 } 88 89 var subworker; 90 onmessage = function (evt) { 91 if (evt.data == 0) { 92 runTests(); 93 return; 94 } 95 96 if (!subworker) { 97 info("Create a subworkers. ID: " + evt.data); 98 subworker = new Worker("worker_messageChannel.js"); 99 subworker.onmessage = function (e) { 100 info("Proxy a message to the parent."); 101 postMessage(e.data, e.ports); 102 }; 103 104 subworker.postMessage(evt.data - 1); 105 return; 106 } 107 108 info("Dispatch a message to the subworker."); 109 subworker.postMessage(evt.data, evt.ports); 110 };