How to use messageChannel method in wpt

Best JavaScript code snippet using wpt

sender_test.js

Source:sender_test.js Github

copy

Full Screen

1/**2 * @license3 * Copyright 2018 Google Inc.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17/**18 * @fileoverview Tests for sender.js.19 */20goog.provide('fireauth.messagechannel.SenderTest');21goog.require('fireauth.messagechannel.Error');22goog.require('fireauth.messagechannel.Sender');23goog.require('fireauth.messagechannel.TimeoutDuration');24goog.require('fireauth.messagechannel.utils');25goog.require('goog.Promise');26goog.require('goog.events.Event');27goog.require('goog.events.EventTarget');28goog.require('goog.testing.MockClock');29goog.require('goog.testing.MockControl');30goog.require('goog.testing.jsunit');31goog.setTestOnly('fireauth.messagechannel.SenderTest');32var mockControl;33var clock;34var ignoreArgument;35function setUp() {36 ignoreArgument = goog.testing.mockmatchers.ignoreArgument;37 mockControl = new goog.testing.MockControl();38 mockControl.$resetAll();39 // Install mock clock.40 clock = new goog.testing.MockClock(true);41}42function tearDown() {43 try {44 mockControl.$verifyAll();45 } finally {46 mockControl.$tearDown();47 }48 goog.dispose(clock);49}50/**51 * @param {!mockControl} mockControl The MockControl reference.52 * @return {!MessageChannel} A mock messagechannel for testing.53 */54function createMockMessageChannel(mockControl) {55 var messageChannel = {56 port1: new goog.events.EventTarget(),57 port2: new goog.events.EventTarget()58 };59 messageChannel.port1.start = mockControl.createFunctionMock('start');60 messageChannel.port1.close = mockControl.createFunctionMock('close');61 return messageChannel;62}63function testSender_messageChannelUnsupported() {64 var postMessage = mockControl.createFunctionMock('postMessage');65 var initializeMessageChannel = mockControl.createMethodMock(66 fireauth.messagechannel.utils, 'initializeMessageChannel');67 initializeMessageChannel().$returns(null);68 postMessage(ignoreArgument, ignoreArgument, ignoreArgument).$never();69 mockControl.$replayAll();70 var sender = new fireauth.messagechannel.Sender({71 'postMessage': postMessage72 });73 return sender.send('myEvent', {'a': 1, 'b': 2})74 .then(fail)75 .thenCatch(function(error) {76 assertEquals(77 fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE,78 error.message);79 });80}81function testSender_send_ackTimeout() {82 var eventId = '12345678';83 var eventType = 'myEvent';84 var data = {'a': 1, 'b': 2};85 var expectedRequest = {86 'eventType': eventType,87 'eventId': eventId,88 'data': data89 };90 var messageChannel = createMockMessageChannel(mockControl);91 var postMessage = mockControl.createFunctionMock('postMessage');92 var initializeMessageChannel = mockControl.createMethodMock(93 fireauth.messagechannel.utils, 'initializeMessageChannel');94 var generateEventId = mockControl.createMethodMock(95 fireauth.messagechannel.utils, 'generateEventId');96 initializeMessageChannel().$returns(messageChannel).$once();97 generateEventId().$returns(eventId).$once();98 messageChannel.port1.start().$once();99 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {100 // Simulate ACK timeout.101 clock.tick(fireauth.messagechannel.TimeoutDuration.ACK);102 }).$once();103 messageChannel.port1.close().$once();104 mockControl.$replayAll();105 var sender = new fireauth.messagechannel.Sender({106 'postMessage': postMessage107 });108 return sender.send(eventType, data)109 .then(fail)110 .thenCatch(function(error) {111 assertEquals(112 fireauth.messagechannel.Error.UNSUPPORTED_EVENT,113 error.message);114 });115}116function testSender_send_ackTimeout_longTimeout() {117 var eventId = '12345678';118 var eventType = 'myEvent';119 var data = {'a': 1, 'b': 2};120 var expectedRequest = {121 'eventType': eventType,122 'eventId': eventId,123 'data': data124 };125 var messageChannel = createMockMessageChannel(mockControl);126 var postMessage = mockControl.createFunctionMock('postMessage');127 var initializeMessageChannel = mockControl.createMethodMock(128 fireauth.messagechannel.utils, 'initializeMessageChannel');129 var generateEventId = mockControl.createMethodMock(130 fireauth.messagechannel.utils, 'generateEventId');131 initializeMessageChannel().$returns(messageChannel).$once();132 generateEventId().$returns(eventId).$once();133 messageChannel.port1.start().$once();134 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {135 // Simulate long ACK timeout.136 clock.tick(fireauth.messagechannel.TimeoutDuration.LONG_ACK);137 }).$once();138 messageChannel.port1.close().$once();139 mockControl.$replayAll();140 var sender = new fireauth.messagechannel.Sender({141 'postMessage': postMessage142 });143 return sender.send(eventType, data, true)144 .then(fail)145 .thenCatch(function(error) {146 assertEquals(147 fireauth.messagechannel.Error.UNSUPPORTED_EVENT,148 error.message);149 });150}151function testSender_send_invalidResponse() {152 var eventId = '12345678';153 var eventType = 'myEvent';154 var data = {'a': 1, 'b': 2};155 var expectedRequest = {156 'eventType': eventType,157 'eventId': eventId,158 'data': data159 };160 var messageChannel = createMockMessageChannel(mockControl);161 var postMessage = mockControl.createFunctionMock('postMessage');162 var initializeMessageChannel = mockControl.createMethodMock(163 fireauth.messagechannel.utils, 'initializeMessageChannel');164 var generateEventId = mockControl.createMethodMock(165 fireauth.messagechannel.utils, 'generateEventId');166 initializeMessageChannel().$returns(messageChannel).$once();167 generateEventId().$returns(eventId).$once();168 messageChannel.port1.start().$once();169 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {170 var event = new goog.events.Event('message');171 // Simulate an invalid response.172 event.data = {173 'eventType': eventType,174 'eventId': eventId,175 'status': 'invalid'176 };177 messageChannel.port1.dispatchEvent(event);178 }).$once();179 messageChannel.port1.close().$once();180 mockControl.$replayAll();181 var sender = new fireauth.messagechannel.Sender({182 'postMessage': postMessage183 });184 return sender.send(eventType, data)185 .then(fail)186 .thenCatch(function(error) {187 assertEquals(188 fireauth.messagechannel.Error.INVALID_RESPONSE,189 error.message);190 });191}192function testSender_send_completionTimeout() {193 var eventId = '12345678';194 var eventType = 'myEvent';195 var data = {'a': 1, 'b': 2};196 var expectedRequest = {197 'eventType': eventType,198 'eventId': eventId,199 'data': data200 };201 var messageChannel = createMockMessageChannel(mockControl);202 var postMessage = mockControl.createFunctionMock('postMessage');203 var initializeMessageChannel = mockControl.createMethodMock(204 fireauth.messagechannel.utils, 'initializeMessageChannel');205 var generateEventId = mockControl.createMethodMock(206 fireauth.messagechannel.utils, 'generateEventId');207 initializeMessageChannel().$returns(messageChannel).$once();208 generateEventId().$returns(eventId).$once();209 messageChannel.port1.start().$once();210 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {211 var event = new goog.events.Event('message');212 event.data = {213 'eventId': eventId,214 'eventType': eventType,215 'status': 'ack'216 };217 // Simulate ACK response sent successfully.218 messageChannel.port1.dispatchEvent(event);219 // Simulate completion response timing out.220 clock.tick(fireauth.messagechannel.TimeoutDuration.COMPLETION);221 }).$once();222 messageChannel.port1.close().$once();223 mockControl.$replayAll();224 var sender = new fireauth.messagechannel.Sender({225 'postMessage': postMessage226 });227 return sender.send(eventType, data)228 .then(fail)229 .thenCatch(function(error) {230 assertEquals(231 fireauth.messagechannel.Error.TIMEOUT,232 error.message);233 });234}235function testSender_send_completionSuccess() {236 var eventId = '12345678';237 var eventType = 'myEvent';238 var data = {'a': 1, 'b': 2};239 var expectedRequest = {240 'eventType': eventType,241 'eventId': eventId,242 'data': data243 };244 var expectedSuccessResponse = [{245 'fulfilled': true,246 'value': {247 'c': 3,248 'd': 4249 }250 }];251 var messageChannel = createMockMessageChannel(mockControl);252 var postMessage = mockControl.createFunctionMock('postMessage');253 var initializeMessageChannel = mockControl.createMethodMock(254 fireauth.messagechannel.utils, 'initializeMessageChannel');255 var generateEventId = mockControl.createMethodMock(256 fireauth.messagechannel.utils, 'generateEventId');257 initializeMessageChannel().$returns(messageChannel).$once();258 generateEventId().$returns(eventId).$once();259 messageChannel.port1.start().$once();260 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {261 var event1 = new goog.events.Event('message');262 var event2 = new goog.events.Event('message');263 event1.data = {264 'eventId': eventId,265 'eventType': eventType,266 'status': 'ack'267 };268 event2.data = {269 'eventId': eventId,270 'eventType': eventType,271 'status': 'done',272 'response': expectedSuccessResponse273 };274 // Simulate successful ACK and DONE responses.275 messageChannel.port1.dispatchEvent(event1);276 messageChannel.port1.dispatchEvent(event2);277 }).$once();278 messageChannel.port1.close().$once();279 mockControl.$replayAll();280 var sender = new fireauth.messagechannel.Sender({281 'postMessage': postMessage282 });283 return sender.send(eventType, data)284 .then(function(result) {285 assertEquals(expectedSuccessResponse, result);286 sender.close();287 // Second call should do nothing.288 sender.close();289 // Connection should not be available anymore.290 return sender.send(eventType, data).then(fail, function(error) {291 assertEquals(292 fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE,293 error.message);294 });295 });296}297function testSender_send_completionSuccess_longTimeout() {298 var eventId = '12345678';299 var eventType = 'myEvent';300 var data = {'a': 1, 'b': 2};301 var expectedRequest = {302 'eventType': eventType,303 'eventId': eventId,304 'data': data305 };306 var expectedSuccessResponse = [{307 'fulfilled': true,308 'value': {309 'c': 3,310 'd': 4311 }312 }];313 var messageChannel = createMockMessageChannel(mockControl);314 var postMessage = mockControl.createFunctionMock('postMessage');315 var initializeMessageChannel = mockControl.createMethodMock(316 fireauth.messagechannel.utils, 'initializeMessageChannel');317 var generateEventId = mockControl.createMethodMock(318 fireauth.messagechannel.utils, 'generateEventId');319 initializeMessageChannel().$returns(messageChannel).$once();320 generateEventId().$returns(eventId).$once();321 messageChannel.port1.start().$once();322 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {323 var event1 = new goog.events.Event('message');324 var event2 = new goog.events.Event('message');325 event1.data = {326 'eventId': eventId,327 'eventType': eventType,328 'status': 'ack'329 };330 event2.data = {331 'eventId': eventId,332 'eventType': eventType,333 'status': 'done',334 'response': expectedSuccessResponse335 };336 // Simulate successful ACK and DONE responses.337 // Long timeout should be applied.338 clock.tick(fireauth.messagechannel.TimeoutDuration.LONG_ACK - 1);339 messageChannel.port1.dispatchEvent(event1);340 clock.tick(fireauth.messagechannel.TimeoutDuration.COMPLETION - 1);341 messageChannel.port1.dispatchEvent(event2);342 }).$once();343 messageChannel.port1.close().$once();344 mockControl.$replayAll();345 var sender = new fireauth.messagechannel.Sender({346 'postMessage': postMessage347 });348 return sender.send(eventType, data, true)349 .then(function(result) {350 assertEquals(expectedSuccessResponse, result);351 sender.close();352 // Second call should do nothing.353 sender.close();354 // Connection should not be available anymore.355 return sender.send(eventType, data).then(fail, function(error) {356 assertEquals(357 fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE,358 error.message);359 });360 });361}362function testSender_send_completionError() {363 var eventId = '12345678';364 var eventType = 'myEvent';365 var data = {'a': 1, 'b': 2};366 var expectedRequest = {367 'eventType': eventType,368 'eventId': eventId,369 'data': data370 };371 var expectedErrorResponse = [{372 'fulfilled': false,373 'reason': 'some error occurred'374 }];375 var messageChannel = createMockMessageChannel(mockControl);376 var postMessage = mockControl.createFunctionMock('postMessage');377 var initializeMessageChannel = mockControl.createMethodMock(378 fireauth.messagechannel.utils, 'initializeMessageChannel');379 var generateEventId = mockControl.createMethodMock(380 fireauth.messagechannel.utils, 'generateEventId');381 initializeMessageChannel().$returns(messageChannel).$once();382 // start called early.383 messageChannel.port1.start().$once();384 generateEventId().$returns(eventId).$once();385 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {386 var event1 = new goog.events.Event('message');387 var event2 = new goog.events.Event('message');388 event1.data = {389 'eventId': eventId,390 'eventType': eventType,391 'status': 'ack'392 };393 event2.data = {394 'eventId': eventId,395 'eventType': eventType,396 'status': 'done',397 'response': expectedErrorResponse398 };399 clock.tick(fireauth.messagechannel.TimeoutDuration.ACK - 1);400 messageChannel.port1.dispatchEvent(event1);401 clock.tick(fireauth.messagechannel.TimeoutDuration.COMPLETION - 1);402 messageChannel.port1.dispatchEvent(event2);403 }).$once();404 messageChannel.port1.close().$once();405 mockControl.$replayAll();406 var sender = new fireauth.messagechannel.Sender({407 'postMessage': postMessage408 });409 return sender.send(eventType, data)410 .then(function(result) {411 assertEquals(expectedErrorResponse, result);412 });413}414function testSender_send_closedConnection() {415 var eventId = '12345678';416 var eventType = 'myEvent';417 var data = {'a': 1, 'b': 2};418 var expectedRequest = {419 'eventType': eventType,420 'eventId': eventId,421 'data': data422 };423 var expectedErrorResponse = {424 'fulfilled': true,425 'value': 'success'426 };427 var messageChannel = createMockMessageChannel(mockControl);428 var postMessage = mockControl.createFunctionMock('postMessage');429 var initializeMessageChannel = mockControl.createMethodMock(430 fireauth.messagechannel.utils, 'initializeMessageChannel');431 var generateEventId = mockControl.createMethodMock(432 fireauth.messagechannel.utils, 'generateEventId');433 initializeMessageChannel().$returns(messageChannel).$once();434 // start called early.435 messageChannel.port1.start().$once();436 generateEventId().$returns(eventId).$once();437 postMessage(expectedRequest, [messageChannel.port2]).$does(function() {438 var event1 = new goog.events.Event('message');439 var event2 = new goog.events.Event('message');440 event1.data = {441 'eventId': eventId,442 'eventType': eventType,443 'status': 'ack'444 };445 event2.data = {446 'eventId': eventId,447 'eventType': eventType,448 'status': 'done',449 'response': expectedErrorResponse450 };451 messageChannel.port1.dispatchEvent(event1);452 // Simulate the connection gets closed.453 sender.close();454 messageChannel.port1.dispatchEvent(event2);455 // Second event will be ignored and the resolver will timeout.456 clock.tick(fireauth.messagechannel.TimeoutDuration.COMPLETION);457 }).$once();458 messageChannel.port1.close().$once();459 messageChannel.port1.close().$once();460 mockControl.$replayAll();461 var sender = new fireauth.messagechannel.Sender({462 'postMessage': postMessage463 });464 return sender.send(eventType, data)465 .then(fail, function(error) {466 assertEquals(467 fireauth.messagechannel.Error.TIMEOUT,468 error.message);469 });470}471function testSender_send_multipleMessages() {472 var eventId1 = '1234';473 var eventType1 = 'myEvent1';474 var data1 = {'request1': 'req1'};475 var expectedRequest1 = {476 'eventType': eventType1,477 'eventId': eventId1,478 'data': data1479 };480 var expectedSuccessResponse1 = [{481 'fulfilled': true,482 'value': {483 'response': 'res1'484 }485 }];486 var eventId2 = '5678';487 var eventType2 = 'myEvent2';488 var data2 = {'request2': 'req2'};489 var expectedRequest2 = {490 'eventType': eventType2,491 'eventId': eventId2,492 'data': data2493 };494 var expectedSuccessResponse2 = [{495 'fulfilled': true,496 'value': {497 'response': 'res2'498 }499 }];500 var eventId3 = '9012';501 var data3 = {'request3': 'req3'};502 var expectedRequest3 = {503 // Test with same event as above.504 'eventType': eventType1,505 'eventId': eventId3,506 'data': data3507 };508 var expectedSuccessResponse3 = [{509 'fulfilled': true,510 'value': {511 'response': 'res3'512 }513 }];514 var messageChannel = createMockMessageChannel(mockControl);515 var messageChannel2 = createMockMessageChannel(mockControl);516 var messageChannel3 = createMockMessageChannel(mockControl);517 var postMessage = mockControl.createFunctionMock('postMessage');518 var initializeMessageChannel = mockControl.createMethodMock(519 fireauth.messagechannel.utils, 'initializeMessageChannel');520 var generateEventId = mockControl.createMethodMock(521 fireauth.messagechannel.utils, 'generateEventId');522 initializeMessageChannel().$returns(messageChannel).$once();523 initializeMessageChannel().$returns(messageChannel2).$once();524 initializeMessageChannel().$returns(messageChannel3).$once();525 generateEventId().$returns(eventId1).$once();526 messageChannel.port1.start().$once();527 generateEventId().$returns(eventId2).$once();528 messageChannel2.port1.start().$once();529 generateEventId().$returns(eventId3).$once();530 messageChannel3.port1.start().$once();531 // First event.532 postMessage(expectedRequest1, [messageChannel.port2]).$does(function() {533 var event1 = new goog.events.Event('message');534 var event2 = new goog.events.Event('message');535 event1.data = {536 'eventId': eventId1,537 'eventType': eventType1,538 'status': 'ack'539 };540 event2.data = {541 'eventId': eventId1,542 'eventType': eventType1,543 'status': 'done',544 'response': expectedSuccessResponse1545 };546 messageChannel.port1.dispatchEvent(event1);547 messageChannel.port1.dispatchEvent(event2);548 }).$once();549 // Second event.550 postMessage(expectedRequest2, [messageChannel2.port2]).$does(function() {551 var event1 = new goog.events.Event('message');552 var event2 = new goog.events.Event('message');553 event1.data = {554 'eventId': eventId2,555 'eventType': eventType2,556 'status': 'ack'557 };558 event2.data = {559 'eventId': eventId2,560 'eventType': eventType2,561 'status': 'done',562 'response': expectedSuccessResponse2563 };564 messageChannel2.port1.dispatchEvent(event1);565 messageChannel2.port1.dispatchEvent(event2);566 }).$once();567 // Third event.568 postMessage(expectedRequest3, [messageChannel3.port2]).$does(function() {569 var event1 = new goog.events.Event('message');570 var event2 = new goog.events.Event('message');571 event1.data = {572 'eventId': eventId3,573 'eventType': eventType1,574 'status': 'ack'575 };576 event2.data = {577 'eventId': eventId3,578 'eventType': eventType1,579 'status': 'done',580 'response': expectedSuccessResponse3581 };582 messageChannel3.port1.dispatchEvent(event1);583 messageChannel3.port1.dispatchEvent(event2);584 }).$once();585 messageChannel.port1.close().$once();586 messageChannel2.port1.close().$once();587 messageChannel3.port1.close().$once();588 mockControl.$replayAll();589 var sender = new fireauth.messagechannel.Sender({590 'postMessage': postMessage591 });592 // goog.Promise.all will fail if a single promise fails.593 // Test with mixture of events (2 types of events). Each request will have a594 // unique event ID.595 return goog.Promise.all(596 [597 sender.send(eventType1, data1),598 sender.send(eventType2, data2),599 sender.send(eventType1, data3)600 ]).then(function(results) {601 assertEquals(3, results.length);602 assertEquals(expectedSuccessResponse1, results[0]);603 assertEquals(expectedSuccessResponse2, results[1]);604 assertEquals(expectedSuccessResponse3, results[2]);605 });...

Full Screen

Full Screen

sender.js

Source:sender.js Github

copy

Full Screen

1/**2 * @license3 * Copyright 2018 Google Inc.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17/**18 * @fileoverview Defines the MessageChannel based wrapper for sending messages19 * to other windows or workers.20 */21goog.provide('fireauth.messagechannel.Sender');22goog.require('fireauth.messagechannel.Error');23goog.require('fireauth.messagechannel.PostMessager');24goog.require('fireauth.messagechannel.Status');25goog.require('fireauth.messagechannel.TimeoutDuration');26goog.require('fireauth.messagechannel.utils');27goog.require('goog.Promise');28goog.require('goog.array');29/**30 * This is the interface defining a MessageChannel/handler pair.31 *32 * @typedef {{33 * onMessage: function(!Event),34 * messageChannel: !MessageChannel35 * }}36 */37fireauth.messagechannel.MessageHandler;38/**39 * Helper static function to create messageChannel errors.40 * @param {!fireauth.messagechannel.Error} errorId The error identifier.41 * @param {?string=} opt_message The optional error message used for generic42 * error types.43 * @return {!Error} The constructed error to return.44 * @private45 */46fireauth.messagechannel.createError_ = function(errorId, opt_message) {47 if (errorId != fireauth.messagechannel.Error.UNKNOWN || !opt_message) {48 return new Error(errorId);49 } else {50 return new Error(opt_message);51 }52};53/**54 * Initializes a channel to send specific messages to a specified PostMessage.55 * @param {!fireauth.messagechannel.PostMessager} postMessager The post messager56 * to send messages to.57 * @constructor58 */59fireauth.messagechannel.Sender = function(postMessager) {60 /**61 * @const @private {!fireauth.messagechannel.PostMessager} The messageChannel62 * PostMessager.63 */64 this.postMessager_ = postMessager;65 /** @private {boolean} Whether the connection was closed. */66 this.closed_ = false;67 /**68 * @const @private {!Array<!fireauth.messagechannel.MessageHandler>} The list69 * of subscribed message handlers and their corresponding MessageChannels.70 */71 this.messageHandlers_ = [];72};73/**74 * Sends a message to the receiver. The message is identified by an event75 * type and can carry additional payload data.76 * The sender protocol works as follows:77 * <ul>78 * <li>The request is constructed and postMessaged to the receiver with the port79 * used to reply back to sender.</li>80 * <li>The operation will block until an ACK response is received. If not, it81 * will timeout and reject with an error.</li>82 * <li>If an ACK response is received, it will wait longer for the full83 * processed response.</li>84 * <li>Once the response is received, the operation will resolve with that85 * result.</li>86 * </ul>87 *88 * @param {string} eventType The event type identifying the message. This is89 * used to help the receiver handle this message.90 * @param {?Object=} opt_data The optional data to send along the message.91 * @param {?boolean=} opt_useLongTimeout Whether long timeout should be used92 * for ACK responses.93 * @return {!goog.Promise<!Array<{fulfilled: boolean,94 * value: (*|undefined),95 * reason: (*|undefined)}>>} A promise that96 * resolves with the receiver responses.97 */98fireauth.messagechannel.Sender.prototype.send = function(99 eventType, opt_data, opt_useLongTimeout) {100 var self = this;101 var eventId;102 var data = opt_data || {};103 var onMessage;104 var ackTimer;105 var completionTimer;106 var entry = null;107 if (this.closed_) {108 return goog.Promise.reject(fireauth.messagechannel.createError_(109 fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE));110 }111 var ackTimeout =112 !!opt_useLongTimeout ?113 fireauth.messagechannel.TimeoutDuration.LONG_ACK :114 fireauth.messagechannel.TimeoutDuration.ACK;115 var messageChannel =116 fireauth.messagechannel.utils.initializeMessageChannel();117 return new goog.Promise(function(resolve, reject) {118 // Send message along with port for reply119 if (messageChannel) {120 eventId = fireauth.messagechannel.utils.generateEventId();121 // Start the connection if not already started.122 messageChannel.port1.start();123 // Handler for receiving message reply from receiver.124 // Blocks promise resolution until service worker detects the change.125 ackTimer = setTimeout(function() {126 // The receiver may not be able to handle the response for various127 // reasons: library not included, or an incompatible version of128 // the library is included.129 // Timeout after some time.130 reject(fireauth.messagechannel.createError_(131 fireauth.messagechannel.Error.UNSUPPORTED_EVENT));132 }, ackTimeout);133 onMessage = function(event) {134 // Process only the expected events that match current event ID.135 if (event.data['eventId'] !== eventId) {136 return;137 }138 // This avoids adding a long wait when the receiver is unable to handle139 // the event.140 if (event.data['status'] === fireauth.messagechannel.Status.ACK) {141 clearTimeout(ackTimer);142 // Set longer timeout to allow receiver to process.143 completionTimer = setTimeout(function() {144 reject(fireauth.messagechannel.createError_(145 fireauth.messagechannel.Error.TIMEOUT));146 }, fireauth.messagechannel.TimeoutDuration.COMPLETION);147 return;148 } else if (event.data['status'] ===149 fireauth.messagechannel.Status.DONE) {150 clearTimeout(completionTimer);151 if (typeof event.data['response'] !== 'undefined') {152 resolve(event.data['response']);153 } else {154 reject(fireauth.messagechannel.createError_(155 fireauth.messagechannel.Error.UNKNOWN));156 }157 } else {158 clearTimeout(ackTimer);159 clearTimeout(completionTimer);160 reject(fireauth.messagechannel.createError_(161 fireauth.messagechannel.Error.INVALID_RESPONSE));162 }163 };164 entry = {165 'messageChannel': messageChannel,166 'onMessage': onMessage167 };168 self.messageHandlers_.push(entry);169 messageChannel.port1.addEventListener('message', onMessage);170 var request = {171 'eventType': eventType,172 'eventId': eventId,173 'data': data174 };175 // It is possible the receiver cannot handle this result.176 // For example, the developer may not be including the library in the177 // receiver or using an outdated version.178 self.postMessager_.postMessage(179 request,180 [messageChannel.port2]);181 } else {182 // No connection available.183 reject(fireauth.messagechannel.createError_(184 fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE));185 }186 }).then(function(result) {187 // On completion, remove the message handler. A new one is needed for a188 // new message.189 self.removeMessageHandler_(entry);190 return result;191 }).thenCatch(function(error) {192 // On failure, remove the message handler. A new one is needed for a new193 // message.194 self.removeMessageHandler_(entry);195 throw error;196 });197};198/**199 * Removes the onMessage handler for the specified messageChannel.200 * @param {?fireauth.messagechannel.MessageHandler} messageHandler201 * @private202 */203fireauth.messagechannel.Sender.prototype.removeMessageHandler_ =204 function(messageHandler) {205 if (!messageHandler) {206 return;207 }208 var messageChannel = messageHandler['messageChannel'];209 var onMessage = messageHandler['onMessage'];210 if (messageChannel) {211 messageChannel.port1.removeEventListener('message', onMessage);212 messageChannel.port1.close();213 }214 goog.array.removeAllIf(this.messageHandlers_, function(ele) {215 return ele == messageHandler;216 });217};218/** Closes the underlying MessageChannel connection. */219fireauth.messagechannel.Sender.prototype.close = function() {220 // Any pending event will timeout.221 while (this.messageHandlers_.length > 0) {222 this.removeMessageHandler_(this.messageHandlers_[0]);223 }224 this.closed_ = true;...

Full Screen

Full Screen

common.js

Source:common.js Github

copy

Full Screen

1/**2* Entry module for building bonsai for a common environment.3*4* It takes care to select the best-suited runner (iframe or worker) environment.5*/6define([7 '../player',8 '../../message_channel',9 '../context/iframe/bootstrap',10 '../context/iframe/context',11 '../context/worker/bootstrap',12 '../context/worker/context',13 '../../renderer/svg/svg',14 '../../tools',15 '../util'16], function(player, MessageChannel, bootstrapIframe, IframeRunnerContext, bootstrapWorker, WorkerRunnerContext, SvgRenderer, tools, bootstrapUtil) {17 'use strict';18 if(typeof window != 'undefined' && window.messageChannel) {19 // This needs to execute async (setTimeout:1) so that20 // IFrameContext.init finishes before this executes:21 setTimeout(function() {22 var messageChannel = window.messageChannel;23 delete window.messageChannel;24 bootstrapIframe(messageChannel, window);25 }, 1);26 } else if(typeof importScripts != 'undefined') {27 // init worker bootstrap28 var messageChannel;29 var notifyRenderer = function(message) {postMessage(message);};30 var onMessage = function(message) {messageChannel.notify(message.data);};31 var disconnect = function() {32 removeEventListener('message', onMessage);33 messageChannel = null;34 };35 messageChannel = new MessageChannel(notifyRenderer, disconnect);36 addEventListener('message', onMessage);37 bootstrapWorker(messageChannel);38 } else {39 window['bonsai'] = player;40 var runnerUrl = bootstrapUtil.getUrl(__bonsaiRunnerCode__);41 player.Renderer = SvgRenderer;42 player.IframeRunnerContext = IframeRunnerContext;43 player.WorkerRunnerContext = WorkerRunnerContext;44 var originalPlayerRun = player.run;45 player.run = tools.hitch(player, function(node, url, options) {46 player.setup({47 baseUrl: player._baseUrl || tools.baseUri(document),48 runnerContext: player.RunnerContext || (runnerUrl ? WorkerRunnerContext : IframeRunnerContext),49 runnerUrl: player.runnerUrl || runnerUrl || ('' + __bonsaiRunnerCode__)50 });51 return originalPlayerRun.apply(player, arguments);52 });53 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var messageChannel = new MessageChannel();2messageChannel.port1.onmessage = function(e) {3 console.log(e.data);4}5messageChannel.port2.postMessage("Hello World!");6window.addEventListener("message", function(e) {7 console.log(e.data);8});9window.postMessage("Hello World!", "*");10var xhr = new XMLHttpRequest();11xhr.setRequestHeader("Content-Type", "text/plain");12xhr.send("Hello World!");13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var messageChannel = new MessageChannel();2messageChannel.port1.onmessage = function(e) {3 console.log(e.data);4};5messageChannel.port2.postMessage('hello world');6var worker = new Worker('worker.js');7worker.onmessage = function(e) {8 console.log(e.data);9};10worker.postMessage('hello world');11self.onmessage = function(e) {12 console.log(e.data);13 self.postMessage('hello back');14};

Full Screen

Using AI Code Generation

copy

Full Screen

1var messageChannel = new MessageChannel();2messageChannel.port1.onmessage = function (event) {3 console.log(event.data);4};5navigator.serviceWorker.controller.postMessage("message", [messageChannel.port2]);6self.addEventListener('message', function (event) {7 var source = event.ports[0];8 source.postMessage("response");9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var messageChannel = new MessageChannel();2messageChannel.port1.onmessage = function(event) {3 var data = event.data;4 console.log("data received: " + data);5}6messageChannel.port2.postMessage("Hello World");7var iframe = document.createElement("iframe");8iframe.src = "test.js";9document.body.appendChild(iframe);10var messageChannel = new MessageChannel();11messageChannel.port1.onmessage = function(event) {12 var data = event.data;13 console.log("data received: " + data);14}15window.postMessage("Hello World", "*", [messageChannel.port2]);

Full Screen

Using AI Code Generation

copy

Full Screen

1var messageChannel = new MessageChannel();2messageChannel.port1.onmessage = function(event) {3 console.log(event.data);4 messageChannel.port2.postMessage("Hello from Worker");5};6messageChannel.port1.start();7messageChannel.port2.start();8postMessage("Hello from main thread", [messageChannel.port2]);9addEventListener('message', function(event) {10 console.log(event.data);11 postMessage("Hello from Worker");12});13onmessage = function(event) {14 console.log(event.data);15 postMessage("Hello from Worker");16};17postMessage("Hello from main thread");18addEventListener('message', function(event) {19 console.log(event.data);20 postMessage("Hello from Worker");21});22onmessage = function(event) {23 console.log(event.data);24 postMessage("Hello from Worker");25};26postMessage("Hello from main thread");27addEventListener('message', function(event) {28 console.log(event.data);29 postMessage("Hello from Worker");30});31onmessage = function(event) {32 console.log(event.data);33 postMessage("Hello from Worker");34};35postMessage("Hello from main thread");36addEventListener('message', function(event) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptoolkit = require('wptoolkit');2var messageChannel = wptoolkit.messageChannel;3messageChannel.sendMessage({msg: 'Hello Parent'});4messageChannel.registerMessageHandler(function(msg) {5 console.log('message received from parent', msg);6});7messageChannel.unregisterMessageHandler();8messageChannel.sendMessageToChild({msg: 'Hello Child'});9messageChannel.registerMessageHandlerFromChild(function(msg) {10 console.log('message received from child', msg);11});12messageChannel.unregisterMessageHandlerFromChild();13messageChannel.sendMessageToParentAndWaitForResponse({msg: 'Hello Parent'}, function(msg) {14 console.log('message received from parent', msg);15});16messageChannel.sendMessageToChildAndWaitForResponse({msg: 'Hello Child'}, function(msg) {17 console.log('message received from child', msg);18});19messageChannel.sendMessageToParentAndWaitForResponse({msg: 'Hello Parent'}, function(msg) {20 console.log('message received from parent', msg);21});22messageChannel.sendMessageToChildAndWaitForResponse({msg: 'Hello Child'}, function(msg) {23 console.log('message received from child', msg);24});25messageChannel.sendMessageToParentAndWaitForResponse({msg: 'Hello Parent'}, function(msg) {26 console.log('message received from parent', msg);27});28messageChannel.sendMessageToChildAndWaitForResponse({msg: 'Hello Child'}, function(msg) {29 console.log('message received from child', msg);30});31messageChannel.sendMessageToParentAndWaitForResponse({msg: 'Hello Parent'}, function(msg) {32 console.log('message received from parent', msg);33});

Full Screen

Using AI Code Generation

copy

Full Screen

1const {ipcRenderer} = require('electron');2var channel = new MessageChannel();3channel.port1.onmessage = function(e) {4 console.log(e.data);5};6ipcRenderer.postMessage('test', [channel.port2]);7const {ipcMain} = require('electron');8ipcMain.on('test', (event, port) => {9 console.log(event);10 port.postMessage('test');11});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful