How to use sendMessageToServer method in Playwright Internal

Best JavaScript code snippet using playwright-internal

conference.js

Source:conference.js Github

copy

Full Screen

...24 if(window.RTCPeerConnection == undefined ) {25 alert('Use latest version of Chrome or Firefox');26 return null;27 }28 function sendMessageToServer(msg) {29 try {30 if(ws !=null || ws != undefined) {31 //console.log('SEND: ' + msg);32 ws.send(msg);33 }34 } catch(e) {35 console.error('exception in websocket send' + e);36 }37 }38 var proto = Conference.prototype;39 proto.mute = function(audio, video) {40 selfObj.rtc.mute(audio, video);41 }42 proto.unmute = function(audio, video) {43 selfObj.rtc.unmute(audio, video);44 }45 proto.getStream = function(audio,video) {46 console.log('audio feed conference', audio);47 console.log(' video feed conference', video);48 selfObj.rtc.getMedia(audio,video);49 }50 proto.switchStream = function(audioSource, videoSource) {51 var sess = confSess.plist[selfObj.wsId];52 if(sess) {53 selfObj.rtc.switchStream(sess, audioSource, videoSource);54 }55 }56 proto.startScrnShare = function(source) {57 if(this.confid && (confSess.state == 3)) {58 selfObj.rtc.getScreenMedia(source, function(err, stream) {59 if(err) {60 selfObj.emit('scrnStream', stream, err);61 return;62 }63 if(stream) {64 window.screenStream = screenStream = stream;65 stream.onended = function(e) {66 console.log('Stream ended ..', e);67 selfObj.stopScrnShare(stream);68 }69 var track = stream.getVideoTracks()[0];70 if(track) {71 track.onended = function(e){72 console.log(' Screenshare Vtrack ended state: '+track.readyState+' kind:'+track.kind, e);73 selfObj.stopScrnShare(stream);74 };75 }76 selfObj.emit('scrnStream', stream);77 if(confSess.via == 'ms') {78 var msg = {'type':'request','method':'addScreen', 'data':{'confid':selfObj.confid, 'name':selfObj.name}};79 sendMessageToServer(JSON.stringify(msg));80 return;81 }82 for(var id in confSess.plist) {83 var sess = confSess.plist[id];84 if(sess) {85 selfObj.rtc.addScreen(sess, stream);86 }87 }88 }89 });90 }91 }92 proto.stopScrnShare = function(lstream) {93 lstream = lstream || screenStream;94 if(lstream){95 if(confSess.state == 3) {96 if(confSess.via == 'ms') {97 var msg = {'type':'request','method':'removeScreen', 'data':{'confid':this.confid, 'name':this.name}};98 sendMessageToServer(JSON.stringify(msg));99 var sess = confSess.plist[selfObj.wsId+'_screen'];100 if(sess) {101 selfObj.rtc.close(sess);102 }103 } else {104 for(var id in confSess.plist) {105 var sess = confSess.plist[id];106 if(sess) {107 selfObj.rtc.removeScreen(sess, lstream);108 }109 }110 }111 }112 this.rtc.stopStream(lstream);113 selfObj.emit('stopScrn', '');114 window.screenStream = screenStream = null;115 }116 }117 proto.updateDetails = function(confid, data) {118 if(this.confid && (confSess.state == 3)) {119 data.confid = this.confid;120 var msg = {'type':'request','method':'updateDetails', 'wsId': this.wsId, 'data':data};121 sendMessageToServer(JSON.stringify(msg));122 }123 }124 proto.onCodeText = function(confid, data) {125 if(this.version < data.ver) {126 this.version = data.ver;127 }128 this.emit('ctext', confid, data.text, data.ver);129 }130 proto.sendCode = function(text) {131 if(this.confid && (confSess.state == 3)) {132 this.lastSent = new Date().getTime();133 this.version++;134 var msg = {'type':'request','method':'ctext', 'wsId': this.wsId, 'data':135 {'confid':this.confid, 'text': text, 'ver':this.version}};136 sendMessageToServer(JSON.stringify(msg));137 }138 }139 proto.sendDirectIM = function(confid, wsId, content) {140 if(confSess.state == 3) {141 var msg = {'type':'request','method':'directIM', 'data':{'confid':this.confid, 'name':this.name, 'wsId':wsId, 'content':content}};142 sendMessageToServer(JSON.stringify(msg));143 }144 }145 proto.sendIM = function(confid, content) {146 if(confSess.state == 3) {147 var msg = {'type':'request','method':'im', 'data':{'confid':this.confid, 'name':this.name, 'content':content}};148 sendMessageToServer(JSON.stringify(msg));149 }150 }151 proto.onRemoteCandidate = function(confid, data) {152 try {153 this.rtc.onCandidate(confSess.plist[data.wsId], data.candidate);154 } catch(e) {155 console.error('Exception in onRemoteCandidate :' , e);156 }157 }158 proto.onRemoteOffer = function(confid, data) {159 try {160 console.log('Got remote Offer');161 if(data.handle) {162 confSess.plist[data.handle] = {'handle' : data.handle, 'type':'listener'};163 this.rtc.onOffer(confSess.plist[data.handle], data.jsep);164 return;165 }166 confSess.plist[data.wsId] = {'wsId': data.wsId, 'name': data.name, 'role': data.role, 'screen':data.screen, 'isRecording': false};167 if(data.role == 'candidate') {168 confSess.cand = confSess.plist[data.wsId];169 confSess.remote = data.name;170 }171 this.rtc.onOffer(confSess.plist[data.wsId], data.jsep);172 this.emit('pjoined', confSess.plist[data.wsId]);173 } catch(e) {174 console.error('Exception in remoteOffer ' , e);175 }176 }177 proto.onRemoveStream = function(confid, data) {178 var sess = confSess.plist[data.wsId];179 if(sess) {180 this.rtc.close(sess);181 this.emit('removeStream', sess);182 }183 delete confSess.plist[data.wsId];184 }185 proto.onPartcipLeft = function(confid, data) {186 try {187 console.log('PLeft conf: ' + confid + ' wsid:' + data.wsId + ' name:' + data.name + ' role: ' + data.role);188 var sess = confSess.plist[data.wsId];189 if(sess) {190 this.rtc.close(sess);191 this.emit('removeStream', sess);192 this.emit('pleft', sess);193 }194 delete confSess.plist[data.wsId];195 }catch(e) {196 console.error('Exception in onPartcipLeft', e);197 }198 }199 proto.onAccepted = function(confid, data) {200 try {201 console.log('call accepted' + confid + ' cand: ' + confSess.cand.name + ' = '+ confSess.cand.wsId);202 this.rtc.createOffer(confSess.plist[confSess.cand.wsId]);203 this.emit('answered', confSess.cand);204 } catch(e) {205 console.error('Exception in onAccepted ' + e);206 }207 }208 proto.onJoinedRoom = function(confid, data) {209 try {210 confSess.plist = confSess.plist || {};211 var sess = {'wsId':selfObj.wsId, 'type':'publisher'};212 confSess.plist[selfObj.wsId] = sess;213 selfObj.rtc.createOffer(sess);214 if((selfObj.role == 'host') && (selfObj.type != 'unlisted')) {215 var sess2 = {'wsId':selfObj.wsId+'_tab', 'type':'publisher_tab'};216 confSess.plist[sess2.wsId] = sess2;217 selfObj.rtc.extStartSession(confSess.id, sess2.wsId, selfObj.role, selfObj.name, sess2);218 }219 } catch(e) {220 console.error('Exception in proto.onJoinedRoom', e);221 }222 }223 proto.onJoined = function(confid, data) {224 try {225 console.log('joined session state: ' + data.state + ' id:' + confid + ' status:' + data.status);226 if(data.status == 'failed' || data.confid == null) {227 console.log(data.status);228 console.log(data.confid);229 alert(data.reason || 'Expired link');230 return;231 }232 confSess.id = this.confid = data.confid;233 confSess.state = 3;234 confSess.plist = data.plist;235 // if(data.state == 3)236 if(data.via == 'ms') {237 } else {238 console.dir(confSess.plist);239 Object.keys(confSess.plist).forEach(function(key, index ) {240 var sess = confSess.plist[key];241 if(sess && (sess.wsId != selfObj.wsId)) {242 setTimeout(function() {243 selfObj.rtc.createOffer(sess);244 }, (1000 * index));245 }246 });247 }248 this.emit('joinedConf', data.confid, data.state, data.status || 'sucesses');249 if(data.text) this.emit('ctext', confid, data.text, data.ver);250 } catch(e) {251 console.error('Exception in onJoined', e);252 }253 }254 proto.answer = function(id) {255 var msg = {'type':'response', 'method':'incomingCall','wsId':this.wsId, 'data':{'confid':this.confid, 'state':3}};256 sendMessageToServer(JSON.stringify(msg));257 confSess.state = 3;258 }259 proto.onIncomingCall = function(id, data) {260 try {261 var from = data.from;262 /*263 if(confSess.isBusy == true) {264 var msg = {'type':'response', 'method':'incomingCall','wsId':this.wsId, 'data':{'confid':id, 'state':4, 'reason':'Already in call'}};265 sendMessageToServer(JSON.stringify(msg));266 console.warn('already in call, so rejecting incoming call from: ' + from);267 return;268 } */269 this.confid = id;270 confSess.id = id;271 confSess.type = 'incoming';272 confSess.remote = from;273 confSess.isBusy = true;274 confSess.state = 2;275 console.log('processing incoming call ' + this.confid + 'from:' + from);276 var msg = {'type':'response', 'method':'incomingCall','wsId':this.wsId, 'data':{'confid':this.confid, 'state':2, 'reason':'Ringing'}};277 sendMessageToServer(JSON.stringify(msg));278 this.emit('incomingcall', id, from);279 } catch(e) {280 console.error('Exception in incomingcall', e);281 }282 }283 proto.onConfStarted = function(data) {284 try {285 confSess = new Object();286 confSess.id = this.confid = data.confid;287 confSess.role = this.role;288 confSess.remote = '';289 confSess.cand = null;290 confSess.plist = new Array();291 confSess.state = 1;292 confSess.via = 'ms';293 this.emit('confstarted', data);294 } catch(e) {295 console.error('Exception in onConfSt ', e);296 }297 }298 proto.startConf = function(interviewType, interviewId, env, authheader) {299 var msg = {'type':'request', 'method':'startConf', 'data':{'name':this.name, 'role': this.role, 'confType':this.type, 'interviewTypeId':interviewType,'interviewId':interviewId, 'env':env, 'authheader':authheader, 'useragent': webrtcDetectedBrowser + '-' + webrtcDetectedVersion}};300 sendMessageToServer(JSON.stringify(msg));301 }302 proto.joinConf = function(confid, role, valid, interviewType, interviewId, env, authheader) {303 //console.log('join conf proto in confeerence, getting confid:' + confid + ' role is:' + this.role);304 this.confid = confid;305 this.interviewType = interviewType;306 this.interviewId = interviewId;307 confSess = new Object();308 confSess.role = this.role;309 confSess.type = this.type;310 confSess.cand = {};311 confSess.plist = [];312 confSess.state = 1;313 confSess.via = 'ms';314 var msg = {'type':'request', 'method':'joinConf', 315 'data':{'name':this.name, 'confid': this.confid, 'role': this.role, 'confType':confSess.type, 316 'interviewTypeId':interviewType,'interviewId' : interviewId, 'env':env, valid:valid, 'authheader':authheader, 'useragent': webrtcDetectedBrowser + '-' + webrtcDetectedVersion}};317 sendMessageToServer(JSON.stringify(msg));318 console.log('Joing conf r:' + this.role);319 }320 proto.leaveConf = function() {321 var msg = {'type':'request', 'method':'leaveConf', 'wsId':this.wsId, 'data':{'confid': this.confid, 'role': this.role}};322 sendMessageToServer(JSON.stringify(msg));323 confSess.state = 5;324 selfObj.stopScrnShare();325 cleanup(this.confid);326 }327 proto.uploader = function(source, data, pname) {328 try {329 if(source ) {330 var msg = {'type':'request', 'method':'stream', 'wsId':this.wsId, 'data':{'confid': this.confid, 'source':source, 'name': pname}};331 ws.send(JSON.stringify(msg));332 }333 console.log('source: ' + source, data)334 if(data != null)335 ws.send(data);336 } catch(e) {337 console.error('Exception in sendFileStream:', e);338 }339 }.bind(this);340 function cleanup(confid) {341 try {342 if(isRecording) {343 //stopRecording();344 }345 console.log('Cleaning the Call ######## ');346 if(screenStream) {347 selfObj.stopScrnShare();348 }349 var parent = document.getElementById("container");350 for(var id in confSess.plist) {351 var sess = confSess.plist[id];352 if(sess) {353 if(sess.wsId.indexOf('_tab')>0) {354 selfObj.rtc.extStopSession(confid, sess.wsId, sess);355 } else {356 selfObj.rtc.close(sess);357 selfObj.emit('removeStream', sess);358 if(sess.stream2) {359 selfObj.emit('removeStream', sess, sess.stream2);360 }361 }362 }363 delete confSess.plist[id];364 }365 delete confSess.plist;366 confSess.plist = [];367 confSess.id = '';368 confSess.type = '';369 confSess.remote = '';370 confSess.state = 0;371 confSess.isBusy = false;372 confSess.iceDone = false;373 selfObj.confid = null;374 selfObj.emit('hangup', confid);375 } catch(e) {376 console.error('Exception in cleanup' + e);377 }378 }379 proto.speaking = function(is_speaking){380 var msg = {'type':'request', 'method':'speaking', 'wsId':this.wsId, 'data': {'confid':this.confid, 'wsId':this.wsId, 'speaking':is_speaking}};381 sendMessageToServer(JSON.stringify(msg));382 }383 proto.hangup = function(){384 try {385 var msg = {'type':'request', 'method':'hangup', 'wsId':this.wsId, 'data':{'confid':this.confid, 'state': (confSess.state > 2)?5:4}};386 sendMessageToServer(JSON.stringify(msg));387 selfObj.stopScrnShare();388 confSess.state = 5;389 cleanup(this.confid);390 } catch(e) {391 console.error('Exception in hangup: ' + e);392 console.dir(confSess);393 }394 }395 proto.register = function() {396 console.log('Registering :' + this.name + 'UA: ' + webrtcDetectedBrowser + '_' +webrtcDetectedVersion);397 var msg = {'type':'request', 'method':'register', 'data':398 {'name':this.name, 'role': this.role, 'sessionId':session, 'useragent': webrtcDetectedBrowser + '-' + webrtcDetectedVersion}};399 sendMessageToServer(JSON.stringify(msg));400 }401 proto.onMessage = function(msg) {402 try {403 if(typeof msg === "string"){404 var json = JSON.parse(msg);405 var data = json.data;406 //console.log('RECV: type:' + json.type + ' method:' + json.method + ' Reason:' + ((data && data.reason)? data.reason:''));407 if(json.type == 'request') {408 switch(json.method){409 case 'ctext' : {410 this.onCodeText(data.confid, data);411 }412 break;413 case 'incomingCall': {414 selfObj.onIncomingCall(data.confid, data);415 }416 break;417 case 'activeCall':418 case 'speaking':419 case 'updateDetails':420 case 'delCall': {421 this.emit(json.method, data);422 }423 break;424 case 'addBuddy':425 case 'delCand':426 case 'addAdmin':427 case 'delBuddy': {428 this.emit(json.method, data.wsId, data.name);429 }430 break;431 case 'dimMsg': {432 this.emit('dimMsg', data);433 }434 break;435 case 'imMsg' : {436 this.emit('imMsg', data.name, data.content);437 }438 break;439 case 'videolist': {440 this.emit('videolist', data.name, data.file);441 }442 break;443 case 'pleft': {444 this.onPartcipLeft(data.confid, data);445 }446 break;447 case 'removestream': {448 this.onRemoveStream(data.confid, data);449 }450 break;451 case 'offer': {452 this.onRemoteOffer(data.confid, data);453 }454 break;455 case 'reoffer': {456 this.rtc.onReOffer(confSess.plist[data.wsId], data.jsep);457 }458 break;459 case 'answer': {460 this.rtc.onAnswer(confSess.plist[data.wsId], data.jsep, confSess.id);461 }462 break;463 case 'reanswer': {464 this.rtc.onReAnswer(confSess.plist[data.wsId], data.jsep, confSess.id);465 }466 break;467 case 'candidate': {468 this.onRemoteCandidate(data.confid, data);469 }470 break;471 default:472 console.log('unhadled request ' + json.method);473 }474 } else if(json.type == 'response') {475 switch(json.method){476 case 'ctext' : {477 }478 break;479 case 'register': {480 try {481 this.wsId = json.wsId;482 console.log('registered with id: ' + this.wsId);483 data.wsId = this.wsId;484 this.emit('connected', data);485 } catch(e) {486 console.error('Execp reg resp', e);487 }488 }489 break;490 case 'startConf': {491 try {492 this.wsId = json.wsId;493 data.wsId = this.wsId;494 this.onConfStarted(data);495 confSess.state = 3;496 } catch(e) {497 console.error('Execp startConf resp', e);498 }499 }500 break;501 case 'im':502 case 'directIM':503 console.log(' msg recv im resp');504 break;505 case 'call':506 case 'callstatus':507 case 'confstatus':{508 if(data.state <= 2) {509 // Trying & Ringing510 } else if(data.state == 3) { // accepted511 confSess.state = 3;512 this.onAccepted(data.confid, data);513 } else if(data.state > 3) {514 console.log('state:' + data.state + ' Reason: ' + data.reason);515 cleanup(data.confid);516 }517 }518 break;519 case 'joinConf': {520 this.wsId = json.wsId;521 this.onJoined(data.confid, data);522 }523 break;524 case 'joinedRoom': {525 this.onJoinedRoom(data.confid, data);526 }527 break;528 case 'addScreen': {529 var sess = {'wsId':selfObj.wsId+'_screen', 'type':'publisher_screen'};530 confSess.plist[sess.wsId] = sess;531 selfObj.rtc.createOffer(sess);532 }533 break;534 case 'addTab' : {535 var sess = {'wsId':selfObj.wsId+'_tab', 'type':'publisher_tab'};536 confSess.plist[sess.wsId] = sess;537 selfObj.rtc.requestTabOffer(sess, confSess.id);538 }539 break540 case 'stream': {541 console.log('file submit sucesses ' + data.file);542 //document.getElementById("submitB").textContent = "Uploaded";543 }544 break;545 case 'answer': {546 this.rtc.onAnswer(confSess.plist[data.wsId], data.jsep, confSess.id);547 }548 break;549 default:550 console.log('unhadled response ' + json.method);551 }552 }553 }554 } catch(e) {555 console.error('Exception in onMessage method:' + json.method, e);556 }557 }558 proto.mutep = function(stream, audio, video) {559 selfObj.rtc.mutep(stream, audio, video);560 }561 proto.unmutep = function(stream, audio, video) {562 selfObj.rtc.unmutep(stream, audio, video);563 }564 proto.connect = function() {565 try {566 ws = new WebSocket(this.url, protocol);567 ws.onopen = function() {568 isConnected = true;569 console.log('websocket opened');570 // setTimeout(selfObj.register, 500);571 selfObj.emit('connected', null);572 // selfObj.rtc.getMedia(); //comment here573 };574 ws.onclose = function() {575 console.log('Webscoket closed');576 isConnected = false;577 ws = null;578 }579 ws.onerror = function(e) {580 console.error('error in websocket connection url: ' + nodeurl + ' e:' + e);581 isConnected = false;582 }583 ws.onmessage = function(event) {584 try {585 if(typeof event.data == 'string') {586 selfObj.onMessage(event.data);587 } else {588 selfObj.onInfileData(event.data);589 }590 } catch(e) {591 console.error('Exception in ws message ' + e);592 }593 }594 } catch(e) {595 console.error('Exception in connect', e);596 }597 }598 proto.on = function(name, cb) {599 try { this.ee.on(name, cb);600 } catch(e) { console.error("[conf:on] excep ", e);601 }602 }603 proto.emit = function(event) {604 this.ee.emit.apply(this.ee, arguments);605 }606 this.rtc.on('offer', function(sess, jsep) {607 var msg = {'type':'request', 'method':'offer', 'wsId': selfObj.wsId,608 'data':{'confid': selfObj.confid, 'wsId': sess.wsId, 'handle':sess.handle, 'type': sess.type, 'jsep':jsep}};609 sendMessageToServer(JSON.stringify(msg));610 });611 this.rtc.on('reoffer', function(sess, jsep) {612 var msg = {'type':'request', 'method':'reoffer', 'wsId': selfObj.wsId,613 'data':{'confid': selfObj.confid, 'wsId': sess.wsId, 'handle':sess.handle, 'jsep':jsep}};614 sendMessageToServer(JSON.stringify(msg));615 });616 this.rtc.on('answer', function(sess, jsep) {617 var msg = {'type':'request', 'method':'answer', 'wsId': selfObj.wsId,618 'data':{'confid': selfObj.confid, 'wsId': sess.wsId, 'handle':sess.handle, 'jsep':jsep}};619 sendMessageToServer(JSON.stringify(msg));620 });621 this.rtc.on('reanswer', function(sess, jsep) {622 var msg = {'type':'request', 'method':'reanswer', 'wsId': selfObj.wsId,623 'data':{'confid': selfObj.confid, 'wsId': sess.wsId, 'handle':sess.handle, 'jsep':jsep}};624 sendMessageToServer(JSON.stringify(msg));625 });626 this.rtc.on('candidate', function(sess, candidate) {627 var msg = {'type':'request', 'method':'candidate', 'wsId': selfObj.wsId,628 'data':{'confid': selfObj.confid, 'wsId': sess.wsId, 'handle':sess.handle, 'type': (sess.type?sess.type:'listener'), 'candidate': candidate}};629 sendMessageToServer(JSON.stringify(msg));630 });631 this.rtc.on('stream', function( stream) {632 // selfObj.register();633 selfObj.emit('stream', stream);634 });635 this.rtc.on('rstream', function(sess, stream) {636 selfObj.emit('remStream', sess, stream);637 });638 this.rtc.on('removestream', function(sess, stream) {639 selfObj.emit('removeStream', sess, stream);640 });641 this.rtc.on('tready', function(sess) {642 var msg = {'type':'request','method':'addTab', 'data':{'confid':selfObj.confid, 'name':selfObj.name}};643 sendMessageToServer(JSON.stringify(msg));644 selfObj.emit('recStarted', sess);645 });646 this.rtc.on('tended', function(sess, stream) {647 var msg = {'type':'request','method':'removeTab', 'data':{'confid':selfObj.confid, 'name':selfObj.name}};648 sendMessageToServer(JSON.stringify(msg));649 });650 this.rtc.on('icecomp', function(sess) {651 confSess.iceDone = true;652 });653 this.rtc.on('error', function(sess) {654 });...

Full Screen

Full Screen

niRemoteUpdateService.Test.Local.js

Source:niRemoteUpdateService.Test.Local.js Github

copy

Full Screen

...58 versionMessage.version = preferredVersion;59 socket.addEventListener('close', function () {60 done();61 });62 updateService.sendMessageToServer(JSON.stringify(versionMessage));63 });64 });65 describe('receives a status update message', function () {66 afterEach(function () {67 expect(updateService.getBlocked()).toBe(true);68 });69 it('that indicates the VI is stopped and blocks the UI', function (done) {70 var statusMessage = {71 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,72 data: {73 status: 'stopped'74 }75 };76 socket.addEventListener('message', function () {77 done();78 });79 updateService.sendMessageToServer(JSON.stringify(statusMessage));80 });81 it('that indicates the VI is paused and blocks the UI', function (done) {82 var statusMessage = {83 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,84 data: {85 status: 'paused'86 }87 };88 socket.addEventListener('message', function () {89 done();90 });91 updateService.sendMessageToServer(JSON.stringify(statusMessage));92 });93 it('that indicates the VI has an error with a message and blocks the UI', function (done) {94 var statusMessage = {95 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,96 errorMessage: 'This is an error message',97 data: {98 status: 'error',99 }100 };101 socket.addEventListener('message', function () {102 done();103 });104 updateService.sendMessageToServer(JSON.stringify(statusMessage));105 });106 it('that indicates the VI has an error without a message and blocks the UI', function (done) {107 var statusMessage = {108 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,109 data: {110 status: 'error'111 }112 };113 socket.addEventListener('message', function () {114 done();115 });116 updateService.sendMessageToServer(JSON.stringify(statusMessage));117 });118 });119 describe('receives a status update message', function () {120 afterEach(function () {121 expect(updateService.getBlocked()).toBe(false);122 });123 it('that indicates the VI is running and unblocks the UI', function (done) {124 var statusMessage = {125 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,126 data: {127 status: 'running'128 }129 };130 socket.addEventListener('message', function () {131 done();132 });133 updateService.sendMessageToServer(JSON.stringify(statusMessage));134 });135 it('with an invalid status', function (done) {136 var statusMessage = {137 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,138 data: {139 status: 'invalid'140 }141 };142 socket.addEventListener('message', function () {143 done();144 });145 updateService.sendMessageToServer(JSON.stringify(statusMessage));146 });147 });148 describe('receives a running status update when the UI is blocked', function () {149 beforeEach(function(done) {150 var stoppedStatusMessage = {151 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,152 data: {153 status: 'stopped'154 }155 };156 socket.addEventListener('message', function () {157 done();158 });159 updateService.sendMessageToServer(JSON.stringify(stoppedStatusMessage));160 });161 afterEach(function() {162 expect(updateService.getBlocked()).toBe(false);163 });164 it('and it unblocks the UI', function (done) {165 var runningStatusMessage = {166 messageType: updateMessageTypeEnum.VI_STATE_UPDATE,167 data: {168 status: 'running'169 }170 };171 socket.addEventListener('message', function () {172 done();173 });174 updateService.sendMessageToServer(JSON.stringify(runningStatusMessage));175 });176 });177 describe('receives a property update message', function() {178 beforeEach(function () {179 var frontPanelControlId = 'id109';180 var frontPanelControlKind = NationalInstruments.HtmlVI.ControlKindEnum.NI_GAUGE;181 var data = {182 value: 1183 };184 this.expectedMessage = {185 messageType: updateMessageTypeEnum.PROPERTY_UPDATE,186 viName: viName,187 frontPanelControlId: frontPanelControlId,188 frontPanelControlKind: frontPanelControlKind,189 data: data190 };191 this.updateMessage = new NationalInstruments.HtmlVI.UpdateMessage();192 this.updateMessage.initAsPropertyUpdateMessage(viName, frontPanelControlId, frontPanelControlKind, data);193 spyOn(console, 'log');194 });195 afterEach(function () {196 expect(console.log).toHaveBeenCalledWith(JSON.stringify(this.expectedMessage));197 });198 it('and applies the property update', function (done) {199 socket.addEventListener('message', function () {200 done();201 });202 updateService.sendMessageToServer(JSON.stringify(this.updateMessage));203 });204 });...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

...30 fillTopicSelect();31 registerUser(publicTopic);32 connectingElement.classList.add('hidden');33 getLast10MessagesFromTopic(publicTopic);34 sendMessageToServer('Joining', 'JOIN', topicInput.value);35 messageInput.focus()36 });37 }38 event.preventDefault();39}40function disconnect() {41 if (stompClient !== null) {42 stompClient.disconnect(function() {43 console.log("Client disconnected");44 });45 stompClient = null;46 }47}48function subscribeToChatMessage(topicId){49 stompClient.subscribe('/topic/chat/sended/' + topicId, function (payload) {50 console.log('### Subscribed to topic ' + topicId);51 onMessageReceived(payload);52 });53}54function unSubscribeAll(){55 for (const sub in stompClient.subscriptions) {56 if (stompClient.subscriptions.hasOwnProperty(sub)) {57 stompClient.unsubscribe(sub);58 }59 }60}61function fillTopicSelect() {62 stompClient.subscribe('/app/chat/topics/subscribe', function (response) {63 var topics = JSON.parse(response.body);64 var select = document.querySelector('#topics-selector');65 66 for (var i = 0; i < topics.length; i += 1) {67 var option = document.createElement("option");68 option.text = topics[i];69 option.value = i;70 select.add(option);71 }72 });73}74function getLast10MessagesFromTopic(topicId) {75 stompClient.subscribe('/app/chat/messages/subscribe/' + topicId, onMessageReceived);76}77function send(event) {78 var messageContent = messageInput.value.trim();79 sendMessageToServer(messageContent, 'CHAT', topicInput.value);80 81 messageInput.value = '';82 event.preventDefault();83}84function sendMessageToServer(message, type, topicValue){85 if(message && stompClient) {86 87 var chatMessage = {88 user: username,89 content: message,90 type: type,91 topicId: topicValue92 }; 93 stompClient.send("/app/chat/send/" + topicValue, {}, JSON.stringify(chatMessage));94 }95}96function registerUser(topicId){97 stompClient.send("/app/chat/register/" + topicId, {},98 JSON.stringify({user: username, type: 'JOIN'})99 )100}101function onMessageReceived(payload) {102 var message = JSON.parse(payload.body);103 104 105 if(message.length > 0){106 for (var i = 0; i < message.length; i += 1) {107 writeMessage(message[i]); 108 writeRanking(message[i]); 109 }110 } else {111 writeMessage(message);112 writeRanking(message); 113 }114 115 sortRanking();116 117}118function writeMessage(message){119 if(message === undefined || message.length === 0 ){120 return;121 }122 123 var messageElement = document.createElement('li');124 125 if(message.type === 'JOIN') {126 messageElement.classList.add('event-message');127 message.content = message.user + ' joined the ' + topicInput.options[topicInput.selectedIndex].text + ' topic';128 } else if (message.type === 'LEAVE') {129 messageElement.classList.add('event-message');130 message.content = message.user + ' left!';131 } else {132 messageElement.classList.add('chat-message');133 var avatarElement = document.createElement('i');134 var avatarText = document.createTextNode(message.user[0]);135 avatarElement.appendChild(avatarText);136 avatarElement.style['background-color'] = getAvatarColor(message.user);137 messageElement.appendChild(avatarElement);138 var usernameElement = document.createElement('span');139 var usernameText = document.createTextNode(message.user);140 usernameElement.appendChild(usernameText);141 messageElement.appendChild(usernameElement);142 }143 var textElement = document.createElement('p');144 var messageText = document.createTextNode(message.content);145 textElement.appendChild(messageText);146 messageElement.appendChild(textElement);147 messageArea.appendChild(messageElement);148 messageArea.scrollTop = messageArea.scrollHeight;149 150}151function sortRanking() {152 var list = document.querySelector("#rankingArea");153 var liList = list.getElementsByTagName("li");154 var sorted;155 var i;156 for (i = 0; i < liList.length - 1; i++) {157 var a = Number(liList[i].dataset.index)158 var b = Number(liList[i + 1].dataset.index)159 160 if ( a < b ) {161 sorted = true;162 break;163 }164 }165 166 if (sorted) {167 liList[i].parentNode.insertBefore(liList[i + 1], liList[i]);168 }169}170function writeRanking(message){171 if(message === undefined || message.length === 0){172 return;173 }174 175 var userRankElement = document.querySelector('#p-'+message.user);176 177 if(userRankElement){178 //document exists179 userRankElement.innerText = message.score;180 var liRanking = document.querySelector('#li-' + message.user);181 liRanking.setAttribute("data-index", message.score);182 183 } else {184 185 var rankingElement = document.createElement('li');186 rankingElement.setAttribute("data-index", message.score);187 rankingElement.setAttribute("id", 'li-' + message.user);188 189 rankingElement.classList.add('user-ranking');190 var avatarElement = document.createElement('i');191 var avatarText = document.createTextNode(message.user[0]);192 avatarElement.appendChild(avatarText);193 avatarElement.style['background-color'] = getAvatarColor(message.user);194 rankingElement.appendChild(avatarElement);195 var usernameElement = document.createElement('span');196 var usernameText = document.createTextNode(message.user);197 usernameElement.appendChild(usernameText);198 rankingElement.appendChild(usernameElement);199 200 201 var textElement = document.createElement('p');202 textElement.setAttribute("id", 'p-' + message.user);203 var messageText = document.createTextNode(message.score);204 textElement.appendChild(messageText);205 206 rankingElement.appendChild(textElement);207 208 rankingArea.appendChild(rankingElement);209 rankingArea.scrollTop = rankingArea.scrollHeight;210 211 }212 213}214function getAvatarColor(messageSender) {215 var hash = 0;216 for (var i = 0; i < messageSender.length; i++) {217 hash = 31 * hash + messageSender.charCodeAt(i);218 }219 var index = Math.abs(hash % colors.length);220 return colors[index];221}222function cleanChatArea() {223 messageArea.innerHTML = "";224}225function onChangeTopic() {226 unSubscribeAll(); 227 sendMessageToServer('Bye', 'LEAVE', previusTopic);228 229 cleanChatArea(); 230 connectingElement.classList.remove('hidden');231 232 subscribeToChatMessage(topicInput.value);233 getLast10MessagesFromTopic(topicInput.value);234 sendMessageToServer('Joining', 'JOIN', topicInput.value);235 236 connectingElement.classList.add('hidden');237}238function storeValue(){239 previusTopic = topicInput.value;240}241usernameForm.addEventListener('submit', connect, true);242messageForm.addEventListener('submit', send, true);243topicInput.addEventListener('change', onChangeTopic, true);...

Full Screen

Full Screen

teleport.js

Source:teleport.js Github

copy

Full Screen

...114 request.pid = value.pid;115 request.other = "";116 delete request.value.pid;117 request.value = JSON.stringify(request.value);118 sendMessageToServer(setUrlNCookie(request,"operationRecord"));119 break;120 case 4:121 case 3: 122 case 5: 123 case 6:124 case 8:125 var value = request.value; 126 request.pid = value.pid;127 request.other = "";128 request.value = value.value;129 sendMessageToServer(setUrlNCookie(request,"operationRecord"));130 break;131 case 2:132 var value = request.value;133 request.pid = value.pid;134 request.other = value.title;135 request.value = value.url;136 sendMessageToServer(setUrlNCookie(request,"operationRecord"));137 break;138 case 1: 139 var value = request.value;140 request.value = getRID();141 request.hosturl = value.hosturl;142 request.objurl = value.objurl;143 sendMessageToServer(setUrlNCookie(request,"pageChange"));144 break;145 case 9:146 var value = request.value;147 var index = isMapHas(value.pid);148 if(index)149 addClickMaptoArr(index,[value.X,value.Y])150 else 151 {152 index = addMapArr(value.pid,value.url,value.title ,value.isSearch);153 addClickMaptoArr(index,[value.X,value.Y]);154 }155 // console.log("已记录点击",value.X,value.Y,value.width,value.height); 156 break;157 case 10:158 var value = request.value;159 var index = isMapHas(value.pid);160 if(index)161 addScrollMaptoArr(index,[value.Y]);162 else 163 {164 index = addMapArr(value.pid,value.url,value.title ,value.isSearch);165 addScrollMaptoArr(index,[value.Y]);166 }167 // console.log("已记录滚动",value.Y,value.width,value.height);168 break;169 case 11:170 var value = request.value;171 var map = getMapfromArr(value.pid);172 request.url = map['url'];173 request.width= value.width;174 request.height= value.height;175 request.title = map['title'];176 request.isSearch = map['isSearch'];177 request.pid = map['pid'];178 request.foucsRecord = value.foucsRecord;179 request.clickData = JSON.stringify(map['clickData']);180 request.scrollData = JSON.stringify(map['scrollData']);181 delete request.value ;182 sendMessageToServer(setUrlNCookie(request,"heatMapData"));183 console.log("提交pid为%s的热力图数据",value.pid);184 break;185 default : 186 sendResponse(request);187 break;188 }...

Full Screen

Full Screen

interface.js

Source:interface.js Github

copy

Full Screen

...3536 },37 sendMessageToServer: function(message){},38 enterAuth: function(){39 this.sendMessageToServer({auth:this.password})40 },41 symbolBtnClass: function(symbol){42 let btnClass = "btn btn-outline-primary";43 if(symbol.symbol == this.symbol)44 btnClass += ' active';45 else46 if(symbol.symbol == this.nextSymbol)47 btnClass = "btn btn-info"48 return btnClass;49 },50 symbolBtnClick: function(symbol){51 // если выбран уже установленный nextSymbol, переключаем на текущий symbol, иначе отправляем выбранный52 if(symbol.symbol == this.nextSymbol)53 this.sendMessageToServer({set:{nextSymbol:this.symbol}})54 else55 if(symbol.symbol != this.symbol){56 this.sendMessageToServer({set:{nextSymbol:symbol.symbol}})57 }58 },59 cancelOrder(id){60 if(confirm('Удалить ордер '+id+'?'))61 this.sendMessageToServer({cancelOrder:id})62 },63 calcProfit: function(){64 profit = 0;65 for(let i in this.orders){66 if(this.orders[i].side == 'BUY' && this.orders[i].status == 'FILLED')67 profit -= this.orders[i].price * this.orders[i].origQty;68 if(this.orders[i].side == 'SELL' && this.orders[i].status == 'NEW')69 profit += this.orders[i].price * this.orders[i].origQty;70 71 }72 return profit73 },74 now: function(){75 return moment().format('D MMM HH:mm:SS')76 },77 getDateTime: function(time,format){78 let date = new Date(time);79 return moment(date).format(format)80 },81 showWallet: function(sym){82 return this.symbol.indexOf(sym)>=0;83 },84 refreshProc: function(){85 this.orders = [];86 this.sendMessageToServer({refresh:1});87 }8889 },90 created: function(){91 self = this92 this.socket = io() 93 this.socket.on('message', message => this.socketOnMessage(message));94 this.sendMessageToServer = function(message){95 console.log('send');96 self.socket.emit('message', message);97 }98 this.sendMessageToServer('get info')99 } ...

Full Screen

Full Screen

Client.js

Source:Client.js Github

copy

Full Screen

...30 //contact the server and create a new game with this definition31 //server must be in initialising state32 createWorld(definition) {33 console.log('[CLIENT] createWorld: ', definition);34 return this.connector.sendMessageToServer('createWorld', definition);35 }36 connect() {37 console.log('[CLIENT] connect');38 return this.connector.sendMessageToServer('connectClient', {name: this.name}).then(initialGameState => {39 this.initialGameState = initialGameState;40 return true;41 })42 }43 setClientSettings(factions, factionId, ready) {44 console.log('[CLIENT] set client settings: ', factions, factionId, ready);45 return this.connector.sendMessageToServer('setClientSettings', {name: this.name, factions, factionId, ready})46 }47 startGame() {48 console.log('[CLIENT] startGame: ');49 return this.connector.sendMessageToServer('startGame', null)50 }51 //in game messages52 setDesiredSpeed = (speed) => {53 console.log('[CLIENT] setDesiredSpeed: ', speed);54 return this.connector.sendMessageToServer('setDesiredSpeed', speed)55 }56 setIsPaused = (isPaused) => {57 return this.connector.sendMessageToServer('setIsPaused', isPaused)58 }59 createColony(bodyId) {60 return this.connector.sendMessageToServer('createColony', bodyId)61 }62 ///////////////////////////////////////63 // Server -> Client message handlers //64 ///////////////////////////////////////65 message_startingGame(gameState) {66 console.log('[CLIENT] startingGame', gameState);67 this.store.dispatch(setSelectedSystemId(+find(gameState.entities, entity => (entity.type === 'system')).id));//TODO base on starting systems68 this.gameState = fromState(gameState, this.initialGameState);69 }70 message_updatingGame(newGameState) {71 //console.log('[CLIENT] updatingGame', newGameState);72 this.gameState = mergeState(this.gameState, newGameState);73 }74 //////////////////...

Full Screen

Full Screen

Lobby.js

Source:Lobby.js Github

copy

Full Screen

...6var players = 1; 7var x;8function refresh(){9 players = 0;10 sendMessageToServer("lobby:playerList:" + gameId);11}12function recruit(){13sendMessageToServer("lobby:role:" + gameId + ":" + client_id + ":recruit");14}15function infantry(){16sendMessageToServer("lobby:role:" + gameId + ":" + client_id + ":infantry");17}18function scout(){19sendMessageToServer("lobby:role:" + gameId + ":" + client_id + ":scout");20}21function artillery(){22sendMessageToServer("lobby:role:" + gameId + ":" + client_id + ":artillery");23}24function changeTimer(ms){25 clearInterval(x);26 x = setInterval(function() {27 ms = ms - 1000;28 var minutes = Math.floor(ms / 60000);29 var seconds = Math.floor((ms % 60000) / 1000);30 if(seconds < 10){31 document.getElementById("time").innerHTML = "Time Until Start - " + minutes + ":0" + seconds; 32 }33 else{34 // Display the result in the element with id="demo"35 document.getElementById("time").innerHTML = "Time Until Start - " + minutes + ":" + seconds;36 }37 }, 1000);38}39function updatePlayerList(name, role, team) {40 //console.log(name);41 var p = document.createElement("P");42 if(team == 1){43 p.style.backgroundColor = "red";44 }45 else if(team == 2){46 p.style.backgroundColor = "blue";47 }48 else if(team == 3){49 p.style.backgroundColor = "green";50 }51 else if(team == 4){52 p.style.backgroundColor = "yellow";53 }54 else if(team == 5){55 p.style.backgroundColor = "purple";56 }57 else if(team == 6){58 p.style.backgroundColor = "pink";59 }60 else if(team == 7){61 p.style.backgroundColor = "orange";62 }63 else if(team == 8){64 p.style.backgroundColor = "LightSkyBlue";65 }66 var t = document.createTextNode(name + " - " + role);67 p.appendChild(t);68 document.getElementById("play").appendChild(p);69}70function connectToServer(){71 //document.getElementById("name").innerHTML = sessionStorage("type");72 serverSocket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');73 serverSocket.onopen = function() {74 //do some initial handshaking, sending back and forth information like the password and starting game state, etc75 sendMessageToServer("lobby:join:" + gameType + ":" + client_id);76 };77 serverSocket.onmessage = message_handler;78}79function sendMessageToServer(msg){80 serverSocket.send(msg);81}82//event listener for when the socket receives a message from the server83//TODO: fix this based on the new model84function message_handler(msg){85 //var i = 1;86 let temp = msg.data.split(":");87 if(temp[0] == "player"){88 document.getElementById("play").innerHTML = "";89 players = 0;90 for(let i = 1; i < temp.length; i+=3){91 updatePlayerList(temp[i], temp[i + 1], temp[i + 2]);92 players++;93 }...

Full Screen

Full Screen

ChatPage.jsx

Source:ChatPage.jsx Github

copy

Full Screen

1import React, { useContext } from 'react';2import { ChatContext } from '../context/ChatContext.js';3import { useParams } from 'react-router-dom';4import ConversationList from '../components/Conversations/ConversationList.jsx';5import ChatDetails from '../components/Chat/ChatDetails.jsx';6import Messages from '../components/Chat/Messages.jsx';7import NewMessage from '../components/Chat/NewMessage.jsx';8import '../components/Chat/Chat.css'; 9function ChatPage() {10 const chatContext = useContext(ChatContext);11 const { messages, isTyping, sendMessageToServer, sendIsTypingToServer, showMessageSent, user } = chatContext;12 const { id } = useParams();13 return (14 15 <div className="content flex_row">16 <ConversationList />17 <div className="chatContainer">18 <ChatDetails />19 <Messages messages={messages} isTyping={isTyping} />20 <NewMessage 21 username={user.username} 22 showMessageSent={showMessageSent}23 sendMessageToServer={sendMessageToServer}24 sendIsTypingToServer={sendIsTypingToServer} 25 />26 </div> 27 </div>28 29 30 )31}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const pw = require('playwright');2(async () => {3 const browser = await pw.chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 window.sendMessageToServer = (message) => {8 console.log(message);9 };10 });11 await page.click('input[name="btnK"]');12 await browser.close();13})();14const express = require('express');15const app = express();16const port = 3000;17app.use(express.json());18app.post('/', (req, res) => {19 console.log(req.body);20 res.send('Hello World!');21});22app.listen(port, () => {23});24const pw = require('playwright');25(async () => {26 const browser = await pw.chromium.launch({headless: false});27 const context = await browser.newContext();28 const page = await context.newPage();29 await page.evaluate(() => {30 window.sendMessageToServer = (message) => {31 console.log(message);32 };33 });34 await page.click('input[name="btnK"]');35 await browser.close();36})();37const express = require('express');38const app = express();39const port = 3000;40app.use(express.json());41app.post('/', (req, res) => {42 console.log(req.body);43 res.send('Hello World!');44});45app.listen(port, () => {46});47const pw = require('playwright');48(async () => {49 const browser = await pw.chromium.launch({headless: false});50 const context = await browser.newContext();51 const page = await context.newPage();52 await page.evaluate(() => {53 window.sendMessageToServer = (message) => {54 console.log(message);55 };56 });57 await page.click('input[name="btnK"]');58 await browser.close();59})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sendMessageToServer } = require('playwright/lib/server/browserType');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await sendMessageToServer(page, 'Page.setDownloadBehavior', {8 });9 await page.click('text=Download my user agent');10 await browser.close();11})();12const { setDefaultDownloadPath } = require('playwright/lib/server/browserContext');13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 await setDefaultDownloadPath(context, '/Users/username/Downloads');18 const page = await context.newPage();19 await page.click('text=Download my user agent');20 await browser.close();21})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;2const browser = await playwright.chromium.launch();3const context = await browser.newContext();4const page = await context.newPage();5await sendMessageToServer(browser, 'targetCreated', {targetInfo: {targetId: 'foo'}});6await browser.close();7const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;8const browser = await playwright.chromium.launch();9const context = await browser.newContext();10const page = await context.newPage();11await sendMessageToServer(browser, 'targetCreated', {targetInfo: {targetId: 'foo'}});12await browser.close();13const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;14const browser = await playwright.chromium.launch();15const context = await browser.newContext();16const page = await context.newPage();17await sendMessageToServer(browser, 'targetCreated', {targetInfo: {targetId: 'foo'}});18await browser.close();19const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;20const browser = await playwright.chromium.launch();21const context = await browser.newContext();22const page = await context.newPage();23await sendMessageToServer(browser, 'targetCreated', {targetInfo: {targetId: 'foo'}});24await browser.close();25const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;26const browser = await playwright.chromium.launch();27const context = await browser.newContext();28const page = await context.newPage();29await sendMessageToServer(browser, 'targetCreated', {targetInfo: {targetId: 'foo'}});30await browser.close();31const sendMessageToServer = require('playwright/lib/server/browserType').sendMessageToServer;32const browser = await playwright.chromium.launch();33const context = await browser.newContext();34const page = await context.newPage();35await sendMessageToServer(browser, 'targetCreated

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { sendMessageToServer } = require('playwright/lib/server/instrumentation');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await sendMessageToServer('some message');8 await browser.close();9})();10const { chromium } = require('playwright');11const { sendMessageToServer } = require('playwright/lib/server/instrumentation');12describe('Playwright Test', () => {13 it('should work', async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await sendMessageToServer('some message');18 await browser.close();19 });20});21import { chromium } from 'playwright';22import { sendMessageToServer } from 'playwright/lib/server/instrumentation';23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await sendMessageToServer('some message');28 await browser.close();29})();30import { chromium } from 'playwright';31import { sendMessageToServer } from 'playwright/lib/server/instrumentation';32describe('Playwright Test', () => {33 it('should work', async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sendMessageToServer } = require('playwright/lib/server/crNetworkManager');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const client = await page.context().newCDPSession(page);8 await sendMessageToServer(client, 'Network.enable');9 await sendMessageToServer(client, 'Network.setExtraHTTPHeaders', { headers: { foo: 'bar' } });10 await sendMessageToServer(client, 'Network.setBlockedURLs', { urls: ['*.css', '*.png'] });11 await sendMessageToServer(client, 'Network.setRequestInterception', { patterns: [{ urlPattern: '*' }] });12})();13const { sendMessageToBrowser } = require('playwright/lib/server/crNetworkManager');14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 const client = await page.context().newCDPSession(page);20 await sendMessageToBrowser(client, 'Network.enable');21 await sendMessageToBrowser(client, 'Network.setExtraHTTPHeaders', { headers: { foo: 'bar' } });22 await sendMessageToBrowser(client, 'Network.setBlockedURLs', { urls: ['*.css', '*.png'] });23 await sendMessageToBrowser(client, 'Network.setRequestInterception', { patterns: [{ urlPattern: '*' }] });24})();25const { sendMessageToBrowser } = require('playwright/lib/server/crNetworkManager');26const { chromium } = require('playwright');27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 const client = await page.context().newCDPSession(page);32 await sendMessageToBrowser(client, 'Network.enable');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sendMessageToServer } = require('playwright/lib/server/webkit');2const { createServer } = require('http');3const { chromium } = require('playwright');4(async () => {5 const server = createServer((req, res) => {6 res.end('Hello World');7 });8 server.listen(0, async () => {9 const port = server.address().port;10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 const client = await page.context().newCDPSession(page);14 await sendMessageToServer(client, 'Network.enable');15 await sendMessageToServer(client, 'Network.setRequestInterception', {16 patterns: [{ urlPattern: '*' }],17 });18 client.on('Network.requestIntercepted', async ({ interceptionId, request }) => {19 await sendMessageToServer(client, 'Network.continueInterceptedRequest', {20 });21 });22 console.log(await page.textContent('body'));23 await browser.close();24 server.close();25 });26})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { sendMessageToServer } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2sendMessageToServer('recorder', 'message', { foo: 'bar' });3const { EventEmitter } = require('events');4const { registerSupplement } = require('playwright/lib/server/supplements/supplement');5const { createGuid } = require('playwright/lib/utils/utils');6class RecorderSupplement extends EventEmitter {7 constructor() {8 super();9 this._recorders = new Map();10 }11 async startRecording(params) {12 const recorderId = createGuid();13 const recorder = new Recorder(params);14 this._recorders.set(recorderId, recorder);15 return { recorderId };16 }17 async stopRecording(params) {18 const { recorderId } = params;19 const recorder = this._recorders.get(recorderId);20 await recorder.stop();21 this._recorders.delete(recorderId);22 return {};23 }24 async sendMessageToClient(message) {25 this.emit('message', message);26 }27}28registerSupplement('recorder', new RecorderSupplement());29class Recorder {30 constructor(params) {31 this._params = params;32 this._recording = false;33 this._recordingPromise = null;34 this._recordingPromiseCallback = null;35 }36 async start() {37 this._recording = true;38 this._recordingPromise = new Promise(f => this._recordingPromiseCallback = f);39 while (this._recording)40 await new Promise(f => setTimeout(f, 1000));41 this._recordingPromiseCallback();42 }43 async stop() {44 this._recording = false;45 await this._recordingPromise;46 }47}48const { EventEmitter } = require('events');49const { registerSupplement } = require('playwright/lib/server/supplements/supplement');50const { createGuid } = require('playwright/lib/utils/utils');51class RecorderSupplement extends EventEmitter {52 constructor() {53 super();54 this._recorders = new Map();55 }56 async startRecording(params) {57 const recorderId = createGuid();58 const recorder = new Recorder(params);59 this._recorders.set(recorderId, recorder);60 return { recorderId };61 }62 async stopRecording(params

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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