Best JavaScript code snippet using playwright-internal
RecordRTC.js
Source: RecordRTC.js
1// ____________2// RecordRTC.js3/**4 * {@link https://github.com/muaz-khan/RecordRTC|RecordRTC} is a WebRTC JavaScript library for audio/video as well as screen activity recording. It supports Chrome, Firefox, Opera, Android, and Microsoft Edge. Platforms: Linux, Mac and Windows.5 * @summary Record audio, video or screen inside the browser.6 * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}7 * @author {@link https://MuazKhan.com|Muaz Khan}8 * @typedef RecordRTC9 * @class10 * @example11 * var recorder = RecordRTC(mediaStream or [arrayOfMediaStream], {12 * type: 'video', // audio or video or gif or canvas13 * recorderType: MediaStreamRecorder || CanvasRecorder || StereoAudioRecorder || Etc14 * });15 * recorder.startRecording();16 * @see For further information:17 * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}18 * @param {MediaStream} mediaStream - Single media-stream object, array of media-streams, html-canvas-element, etc.19 * @param {object} config - {type:"video", recorderType: MediaStreamRecorder, disableLogs: true, numberOfAudioChannels: 1, bufferSize: 0, sampleRate: 0, desiredSampRate: 16000, video: HTMLVideoElement, etc.}20 */21function RecordRTC(mediaStream, config) {22 if (!mediaStream) {23 throw 'First parameter is required.';24 }25 config = config || {26 type: 'video'27 };28 config = new RecordRTCConfiguration(mediaStream, config);29 // a reference to user's recordRTC object30 var self = this;31 function startRecording(config) {32 if (!config.disableLogs) {33 console.log('RecordRTC version: ', self.version);34 }35 if (!!config2) {36 // allow users to set options using startRecording method37 // config2 is similar to main "config" object (second parameter over RecordRTC constructor)38 config = new RecordRTCConfiguration(mediaStream, config2);39 }40 if (!config.disableLogs) {41 console.log('started recording ' + config.type + ' stream.');42 }43 if (mediaRecorder) {44 mediaRecorder.clearRecordedData();45 mediaRecorder.record();46 setState('recording');47 if (self.recordingDuration) {48 handleRecordingDuration();49 }50 return self;51 }52 initRecorder(function() {53 if (self.recordingDuration) {54 handleRecordingDuration();55 }56 });57 return self;58 }59 function initRecorder(initCallback) {60 if (initCallback) {61 config.initCallback = function() {62 initCallback();63 initCallback = config.initCallback = null; // recorder.initRecorder should be call-backed once.64 };65 }66 var Recorder = new GetRecorderType(mediaStream, config);67 mediaRecorder = new Recorder(mediaStream, config);68 mediaRecorder.record();69 setState('recording');70 if (!config.disableLogs) {71 console.log('Initialized recorderType:', mediaRecorder.constructor.name, 'for output-type:', config.type);72 }73 }74 function stopRecording(callback) {75 callback = callback || function() {};76 if (!mediaRecorder) {77 warningLog();78 return;79 }80 if (self.state === 'paused') {81 self.resumeRecording();82 setTimeout(function() {83 stopRecording(callback);84 }, 1);85 return;86 }87 if (self.state !== 'recording' && !config.disableLogs) {88 console.warn('Recording state should be: "recording", however current state is: ', self.state);89 }90 if (!config.disableLogs) {91 console.log('Stopped recording ' + config.type + ' stream.');92 }93 if (config.type !== 'gif') {94 mediaRecorder.stop(_callback);95 } else {96 mediaRecorder.stop();97 _callback();98 }99 setState('stopped');100 function _callback(__blob) {101 if (!mediaRecorder) {102 if (typeof callback.call === 'function') {103 callback.call(self, '');104 } else {105 callback('');106 }107 return;108 }109 Object.keys(mediaRecorder).forEach(function(key) {110 if (typeof mediaRecorder[key] === 'function') {111 return;112 }113 self[key] = mediaRecorder[key];114 });115 var blob = mediaRecorder.blob;116 if (!blob) {117 if (__blob) {118 mediaRecorder.blob = blob = __blob;119 } else {120 throw 'Recording failed.';121 }122 }123 if (blob && !config.disableLogs) {124 console.log(blob.type, '->', bytesToSize(blob.size));125 }126 if (callback) {127 var url;128 try {129 url = URL.createObjectURL(blob);130 } catch (e) {}131 if (typeof callback.call === 'function') {132 callback.call(self, url);133 } else {134 callback(url);135 }136 }137 if (!config.autoWriteToDisk) {138 return;139 }140 getDataURL(function(dataURL) {141 var parameter = {};142 parameter[config.type + 'Blob'] = dataURL;143 DiskStorage.Store(parameter);144 });145 }146 }147 function pauseRecording() {148 if (!mediaRecorder) {149 warningLog();150 return;151 }152 if (self.state !== 'recording') {153 if (!config.disableLogs) {154 console.warn('Unable to pause the recording. Recording state: ', self.state);155 }156 return;157 }158 setState('paused');159 mediaRecorder.pause();160 if (!config.disableLogs) {161 console.log('Paused recording.');162 }163 }164 function resumeRecording() {165 if (!mediaRecorder) {166 warningLog();167 return;168 }169 if (self.state !== 'paused') {170 if (!config.disableLogs) {171 console.warn('Unable to resume the recording. Recording state: ', self.state);172 }173 return;174 }175 setState('recording');176 // not all libs have this method yet177 mediaRecorder.resume();178 if (!config.disableLogs) {179 console.log('Resumed recording.');180 }181 }182 function readFile(_blob) {183 postMessage(new FileReaderSync().readAsDataURL(_blob));184 }185 function getDataURL(callback, _mediaRecorder) {186 if (!callback) {187 throw 'Pass a callback function over getDataURL.';188 }189 var blob = _mediaRecorder ? _mediaRecorder.blob : (mediaRecorder || {}).blob;190 if (!blob) {191 if (!config.disableLogs) {192 console.warn('Blob encoder did not finish its job yet.');193 }194 setTimeout(function() {195 getDataURL(callback, _mediaRecorder);196 }, 1000);197 return;198 }199 if (typeof Worker !== 'undefined' && !navigator.mozGetUserMedia) {200 var webWorker = processInWebWorker(readFile);201 webWorker.onmessage = function(event) {202 callback(event.data);203 };204 webWorker.postMessage(blob);205 } else {206 var reader = new FileReader();207 reader.readAsDataURL(blob);208 reader.onload = function(event) {209 callback(event.target.result);210 };211 }212 function processInWebWorker(_function) {213 try {214 var blob = URL.createObjectURL(new Blob([_function.toString(),215 'this.onmessage = function (eee) {' + _function.name + '(eee.data);}'216 ], {217 type: 'application/javascript'218 }));219 var worker = new Worker(blob);220 URL.revokeObjectURL(blob);221 return worker;222 } catch (e) {}223 }224 }225 function handleRecordingDuration(counter) {226 counter = counter || 0;227 if (self.state === 'paused') {228 setTimeout(function() {229 handleRecordingDuration(counter);230 }, 1000);231 return;232 }233 if (self.state === 'stopped') {234 return;235 }236 if (counter >= self.recordingDuration) {237 stopRecording(self.onRecordingStopped);238 return;239 }240 counter += 1000; // 1-second241 setTimeout(function() {242 handleRecordingDuration(counter);243 }, 1000);244 }245 function setState(state) {246 if (!self) {247 return;248 }249 self.state = state;250 if (typeof self.onStateChanged.call === 'function') {251 self.onStateChanged.call(self, state);252 } else {253 self.onStateChanged(state);254 }255 }256 var WARNING = 'It seems that recorder is destroyed or "startRecording" is not invoked for ' + config.type + ' recorder.';257 function warningLog() {258 if (config.disableLogs === true) {259 return;260 }261 console.warn(WARNING);262 }263 var mediaRecorder;264 var returnObject = {265 /**266 * This method starts the recording.267 * @method268 * @memberof RecordRTC269 * @instance270 * @example271 * var recorder = RecordRTC(mediaStream, {272 * type: 'video'273 * });274 * recorder.startRecording();275 */276 startRecording: startRecording,277 /**278 * This method stops the recording. It is strongly recommended to get "blob" or "URI" inside the callback to make sure all recorders finished their job.279 * @param {function} callback - Callback to get the recorded blob.280 * @method281 * @memberof RecordRTC282 * @instance283 * @example284 * recorder.stopRecording(function() {285 * // use either "this" or "recorder" object; both are identical286 * video.src = this.toURL();287 * var blob = this.getBlob();288 * });289 */290 stopRecording: stopRecording,291 /**292 * This method pauses the recording. You can resume recording using "resumeRecording" method.293 * @method294 * @memberof RecordRTC295 * @instance296 * @todo Firefox is unable to pause the recording. Fix it.297 * @example298 * recorder.pauseRecording(); // pause the recording299 * recorder.resumeRecording(); // resume again300 */301 pauseRecording: pauseRecording,302 /**303 * This method resumes the recording.304 * @method305 * @memberof RecordRTC306 * @instance307 * @example308 * recorder.pauseRecording(); // first of all, pause the recording309 * recorder.resumeRecording(); // now resume it310 */311 resumeRecording: resumeRecording,312 /**313 * This method initializes the recording.314 * @method315 * @memberof RecordRTC316 * @instance317 * @todo This method should be deprecated.318 * @example319 * recorder.initRecorder();320 */321 initRecorder: initRecorder,322 /**323 * Ask RecordRTC to auto-stop the recording after 5 minutes.324 * @method325 * @memberof RecordRTC326 * @instance327 * @example328 * var fiveMinutes = 5 * 1000 * 60;329 * recorder.setRecordingDuration(fiveMinutes, function() {330 * var blob = this.getBlob();331 * video.src = this.toURL();332 * });333 *334 * // or otherwise335 * recorder.setRecordingDuration(fiveMinutes).onRecordingStopped(function() {336 * var blob = this.getBlob();337 * video.src = this.toURL();338 * });339 */340 setRecordingDuration: function(recordingDuration, callback) {341 if (typeof recordingDuration === 'undefined') {342 throw 'recordingDuration is required.';343 }344 if (typeof recordingDuration !== 'number') {345 throw 'recordingDuration must be a number.';346 }347 self.recordingDuration = recordingDuration;348 self.onRecordingStopped = callback || function() {};349 return {350 onRecordingStopped: function(callback) {351 self.onRecordingStopped = callback;352 }353 };354 },355 /**356 * This method can be used to clear/reset all the recorded data.357 * @method358 * @memberof RecordRTC359 * @instance360 * @todo Figure out the difference between "reset" and "clearRecordedData" methods.361 * @example362 * recorder.clearRecordedData();363 */364 clearRecordedData: function() {365 if (!mediaRecorder) {366 warningLog();367 return;368 }369 mediaRecorder.clearRecordedData();370 if (!config.disableLogs) {371 console.log('Cleared old recorded data.');372 }373 },374 /**375 * Get the recorded blob. Use this method inside the "stopRecording" callback.376 * @method377 * @memberof RecordRTC378 * @instance379 * @example380 * recorder.stopRecording(function() {381 * var blob = this.getBlob();382 *383 * var file = new File([blob], 'filename.webm', {384 * type: 'video/webm'385 * });386 *387 * var formData = new FormData();388 * formData.append('file', file); // upload "File" object rather than a "Blob"389 * uploadToServer(formData);390 * });391 * @returns {Blob} Returns recorded data as "Blob" object.392 */393 getBlob: function() {394 if (!mediaRecorder) {395 warningLog();396 return;397 }398 return mediaRecorder.blob;399 },400 /**401 * Get data-URI instead of Blob.402 * @param {function} callback - Callback to get the Data-URI.403 * @method404 * @memberof RecordRTC405 * @instance406 * @example407 * recorder.stopRecording(function() {408 * recorder.getDataURL(function(dataURI) {409 * video.src = dataURI;410 * });411 * });412 */413 getDataURL: getDataURL,414 /**415 * Get virtual/temporary URL. Usage of this URL is limited to current tab.416 * @method417 * @memberof RecordRTC418 * @instance419 * @example420 * recorder.stopRecording(function() {421 * video.src = this.toURL();422 * });423 * @returns {String} Returns a virtual/temporary URL for the recorded "Blob".424 */425 toURL: function() {426 if (!mediaRecorder) {427 warningLog();428 return;429 }430 return URL.createObjectURL(mediaRecorder.blob);431 },432 /**433 * Get internal recording object (i.e. internal module) e.g. MutliStreamRecorder, MediaStreamRecorder, StereoAudioRecorder or WhammyRecorder etc.434 * @method435 * @memberof RecordRTC436 * @instance437 * @example438 * var internalRecorder = recorder.getInternalRecorder();439 * if(internalRecorder instanceof MultiStreamRecorder) {440 * internalRecorder.addStreams([newAudioStream]);441 * internalRecorder.resetVideoStreams([screenStream]);442 * }443 * @returns {Object} Returns internal recording object.444 */445 getInternalRecorder: function() {446 return mediaRecorder;447 },448 /**449 * Invoke save-as dialog to save the recorded blob into your disk.450 * @param {string} fileName - Set your own file name.451 * @method452 * @memberof RecordRTC453 * @instance454 * @example455 * recorder.stopRecording(function() {456 * this.save('file-name');457 *458 * // or manually:459 * invokeSaveAsDialog(this.getBlob(), 'filename.webm');460 * });461 */462 save: function(fileName) {463 if (!mediaRecorder) {464 warningLog();465 return;466 }467 invokeSaveAsDialog(mediaRecorder.blob, fileName);468 },469 /**470 * This method gets a blob from indexed-DB storage.471 * @param {function} callback - Callback to get the recorded blob.472 * @method473 * @memberof RecordRTC474 * @instance475 * @example476 * recorder.getFromDisk(function(dataURL) {477 * video.src = dataURL;478 * });479 */480 getFromDisk: function(callback) {481 if (!mediaRecorder) {482 warningLog();483 return;484 }485 RecordRTC.getFromDisk(config.type, callback);486 },487 /**488 * This method appends an array of webp images to the recorded video-blob. It takes an "array" object.489 * @type {Array.<Array>}490 * @param {Array} arrayOfWebPImages - Array of webp images.491 * @method492 * @memberof RecordRTC493 * @instance494 * @todo This method should be deprecated.495 * @example496 * var arrayOfWebPImages = [];497 * arrayOfWebPImages.push({498 * duration: index,499 * image: 'data:image/webp;base64,...'500 * });501 * recorder.setAdvertisementArray(arrayOfWebPImages);502 */503 setAdvertisementArray: function(arrayOfWebPImages) {504 config.advertisement = [];505 var length = arrayOfWebPImages.length;506 for (var i = 0; i < length; i++) {507 config.advertisement.push({508 duration: i,509 image: arrayOfWebPImages[i]510 });511 }512 },513 /**514 * It is equivalent to <code class="str">"recorder.getBlob()"</code> method. Usage of "getBlob" is recommended, though.515 * @property {Blob} blob - Recorded Blob can be accessed using this property.516 * @memberof RecordRTC517 * @instance518 * @readonly519 * @example520 * recorder.stopRecording(function() {521 * var blob = this.blob;522 *523 * // below one is recommended524 * var blob = this.getBlob();525 * });526 */527 blob: null,528 /**529 * This works only with {recorderType:StereoAudioRecorder}. Use this property on "stopRecording" to verify the encoder's sample-rates.530 * @property {number} bufferSize - Buffer-size used to encode the WAV container531 * @memberof RecordRTC532 * @instance533 * @readonly534 * @example535 * recorder.stopRecording(function() {536 * alert('Recorder used this buffer-size: ' + this.bufferSize);537 * });538 */539 bufferSize: 0,540 /**541 * This works only with {recorderType:StereoAudioRecorder}. Use this property on "stopRecording" to verify the encoder's sample-rates.542 * @property {number} sampleRate - Sample-rates used to encode the WAV container543 * @memberof RecordRTC544 * @instance545 * @readonly546 * @example547 * recorder.stopRecording(function() {548 * alert('Recorder used these sample-rates: ' + this.sampleRate);549 * });550 */551 sampleRate: 0,552 /**553 * {recorderType:StereoAudioRecorder} returns ArrayBuffer object.554 * @property {ArrayBuffer} buffer - Audio ArrayBuffer, supported only in Chrome.555 * @memberof RecordRTC556 * @instance557 * @readonly558 * @example559 * recorder.stopRecording(function() {560 * var arrayBuffer = this.buffer;561 * alert(arrayBuffer.byteLength);562 * });563 */564 buffer: null,565 /**566 * This method resets the recorder. So that you can reuse single recorder instance many times.567 * @method568 * @memberof RecordRTC569 * @instance570 * @example571 * recorder.reset();572 * recorder.startRecording();573 */574 reset: function() {575 if (self.state === 'recording' && !config.disableLogs) {576 console.warn('Stop an active recorder.');577 }578 if (mediaRecorder && typeof mediaRecorder.clearRecordedData === 'function') {579 mediaRecorder.clearRecordedData();580 }581 mediaRecorder = null;582 setState('inactive');583 self.blob = null;584 },585 /**586 * This method is called whenever recorder's state changes. Use this as an "event".587 * @property {String} state - A recorder's state can be: recording, paused, stopped or inactive.588 * @method589 * @memberof RecordRTC590 * @instance591 * @example592 * recorder.onStateChanged = function(state) {593 * console.log('Recorder state: ', state);594 * };595 */596 onStateChanged: function(state) {597 if (!config.disableLogs) {598 console.log('Recorder state changed:', state);599 }600 },601 /**602 * A recorder can have inactive, recording, paused or stopped states.603 * @property {String} state - A recorder's state can be: recording, paused, stopped or inactive.604 * @memberof RecordRTC605 * @static606 * @readonly607 * @example608 * // this looper function will keep you updated about the recorder's states.609 * (function looper() {610 * document.querySelector('h1').innerHTML = 'Recorder\'s state is: ' + recorder.state;611 * if(recorder.state === 'stopped') return; // ignore+stop612 * setTimeout(looper, 1000); // update after every 3-seconds613 * })();614 * recorder.startRecording();615 */616 state: 'inactive',617 /**618 * Get recorder's readonly state.619 * @method620 * @memberof RecordRTC621 * @example622 * var state = recorder.getState();623 * @returns {String} Returns recording state.624 */625 getState: function() {626 return self.state;627 },628 /**629 * Destroy RecordRTC instance. Clear all recorders and objects.630 * @method631 * @memberof RecordRTC632 * @example633 * recorder.destroy();634 */635 destroy: function() {636 var disableLogsCache = config.disableLogs;637 config = {638 disableLogs: true639 };640 self.reset();641 setState('destroyed');642 returnObject = self = null;643 if (Storage.AudioContextConstructor) {644 Storage.AudioContextConstructor.close();645 Storage.AudioContextConstructor = null;646 }647 config.disableLogs = disableLogsCache;648 if (!config.disableLogs) {649 console.log('RecordRTC is destroyed.');650 }651 },652 /**653 * RecordRTC version number654 * @property {String} version - Release version number.655 * @memberof RecordRTC656 * @static657 * @readonly658 * @example659 * alert(recorder.version);660 */661 version: '@@version'662 };663 if (!this) {664 self = returnObject;665 return returnObject;666 }667 // if someone wants to use RecordRTC with the "new" keyword.668 for (var prop in returnObject) {669 this[prop] = returnObject[prop];670 }671 self = this;672 return returnObject;673}674RecordRTC.version = '@@version';675if (typeof module !== 'undefined' /* && !!module.exports*/ ) {676 module.exports = RecordRTC;677}678if (typeof define === 'function' && define.amd) {679 define('RecordRTC', [], function() {680 return RecordRTC;681 });...
MediaStreamRecorder.js
Source: MediaStreamRecorder.js
1// ______________________2// MediaStreamRecorder.js3// todo: need to show alert boxes for incompatible cases4// encoder only supports 48k/16k mono audio channel5/*6 * Implementation of https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html7 * The MediaRecorder accepts a mediaStream as input source passed from UA. When recorder starts,8 * a MediaEncoder will be created and accept the mediaStream as input source.9 * Encoder will get the raw data by track data changes, encode it by selected MIME Type, then store the encoded in EncodedBufferCache object.10 * The encoded data will be extracted on every timeslice passed from Start function call or by RequestData function.11 * Thread model:12 * When the recorder starts, it creates a "Media Encoder" thread to read data from MediaEncoder object and store buffer in EncodedBufferCache object.13 * Also extract the encoded data and create blobs on every timeslice passed from start function or RequestData function called by UA.14 */15/**16 * MediaStreamRecorder is an abstraction layer for "MediaRecorder API". It is used by {@link RecordRTC} to record MediaStream(s) in Firefox.17 * @summary Runs top over MediaRecorder API.18 * @license {@link https://github.com/muaz-khan/RecordRTC#license|MIT}19 * @author {@link http://www.MuazKhan.com|Muaz Khan}20 * @typedef MediaStreamRecorder21 * @class22 * @example23 * var options = {24 * mimeType: 'video/mp4', // audio/ogg or video/webm25 * audioBitsPerSecond : 256 * 8 * 1024,26 * videoBitsPerSecond : 256 * 8 * 1024,27 * bitsPerSecond: 256 * 8 * 1024, // if this is provided, skip above two28 * getNativeBlob: true // by default it is false29 * }30 * var recorder = new MediaStreamRecorder(MediaStream, options);31 * recorder.record();32 * recorder.stop(function(blob) {33 * video.src = URL.createObjectURL(blob);34 *35 * // or36 * var blob = recorder.blob;37 * });38 * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}39 * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.40 * @param {object} config - {disableLogs:true, initCallback: function, mimeType: "video/webm", onAudioProcessStarted: function}41 */42function MediaStreamRecorder(mediaStream, config) {43 var self = this;44 config = config || {45 // bitsPerSecond: 256 * 8 * 1024,46 mimeType: 'video/webm'47 };48 if (config.type === 'audio') {49 if (mediaStream.getVideoTracks().length && mediaStream.getAudioTracks().length) {50 var stream;51 if (!!navigator.mozGetUserMedia) {52 stream = new MediaStream();53 stream.addTrack(mediaStream.getAudioTracks()[0]);54 } else {55 // webkitMediaStream56 stream = new MediaStream(mediaStream.getAudioTracks());57 }58 mediaStream = stream;59 }60 if (!config.mimeType || config.mimeType.indexOf('audio') === -1) {61 config.mimeType = isChrome ? 'audio/webm' : 'audio/ogg';62 }63 }64 /**65 * This method records MediaStream.66 * @method67 * @memberof MediaStreamRecorder68 * @example69 * recorder.record();70 */71 this.record = function() {72 self.blob = null;73 var recorderHints = config;74 if (!config.disableLogs) {75 console.log('Passing following config over MediaRecorder API.', recorderHints);76 }77 if (mediaRecorder) {78 // mandatory to make sure Firefox doesn't fails to record streams 3-4 times without reloading the page.79 mediaRecorder = null;80 }81 if (isChrome && !isMediaRecorderCompatible()) {82 // to support video-only recording on stable83 recorderHints = 'video/vp8';84 }85 // http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp86 // https://wiki.mozilla.org/Gecko:MediaRecorder87 // https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html88 // starting a recording session; which will initiate "Reading Thread"89 // "Reading Thread" are used to prevent main-thread blocking scenarios90 try {91 mediaRecorder = new MediaRecorder(mediaStream, recorderHints);92 } catch (e) {93 mediaRecorder = new MediaRecorder(mediaStream);94 }95 if ('canRecordMimeType' in mediaRecorder && mediaRecorder.canRecordMimeType(config.mimeType) === false) {96 if (!config.disableLogs) {97 console.warn('MediaRecorder API seems unable to record mimeType:', config.mimeType);98 }99 }100 // i.e. stop recording when <video> is paused by the user; and auto restart recording 101 // when video is resumed. E.g. yourStream.getVideoTracks()[0].muted = true; // it will auto-stop recording.102 mediaRecorder.ignoreMutedMedia = config.ignoreMutedMedia || false;103 // Dispatching OnDataAvailable Handler104 mediaRecorder.ondataavailable = function(e) {105 if (self.dontFireOnDataAvailableEvent) {106 return;107 }108 if (!e.data || !e.data.size || e.data.size < 100 || self.blob) {109 return;110 }111 /**112 * @property {Blob} blob - Recorded frames in video/webm blob.113 * @memberof MediaStreamRecorder114 * @example115 * recorder.stop(function() {116 * var blob = recorder.blob;117 * });118 */119 self.blob = config.getNativeBlob ? e.data : new Blob([e.data], {120 type: config.mimeType || 'video/webm'121 });122 if (self.recordingCallback) {123 self.recordingCallback(self.blob);124 self.recordingCallback = null;125 }126 };127 mediaRecorder.onerror = function(error) {128 if (!config.disableLogs) {129 if (error.name === 'InvalidState') {130 console.error('The MediaRecorder is not in a state in which the proposed operation is allowed to be executed.');131 } else if (error.name === 'OutOfMemory') {132 console.error('The UA has exhaused the available memory. User agents SHOULD provide as much additional information as possible in the message attribute.');133 } else if (error.name === 'IllegalStreamModification') {134 console.error('A modification to the stream has occurred that makes it impossible to continue recording. An example would be the addition of a Track while recording is occurring. User agents SHOULD provide as much additional information as possible in the message attribute.');135 } else if (error.name === 'OtherRecordingError') {136 console.error('Used for an fatal error other than those listed above. User agents SHOULD provide as much additional information as possible in the message attribute.');137 } else if (error.name === 'GenericError') {138 console.error('The UA cannot provide the codec or recording option that has been requested.', error);139 } else {140 console.error('MediaRecorder Error', error);141 }142 }143 // When the stream is "ended" set recording to 'inactive' 144 // and stop gathering data. Callers should not rely on 145 // exactness of the timeSlice value, especially 146 // if the timeSlice value is small. Callers should 147 // consider timeSlice as a minimum value148 if (mediaRecorder.state !== 'inactive' && mediaRecorder.state !== 'stopped') {149 mediaRecorder.stop();150 }151 };152 // void start(optional long mTimeSlice)153 // The interval of passing encoded data from EncodedBufferCache to onDataAvailable154 // handler. "mTimeSlice < 0" means Session object does not push encoded data to155 // onDataAvailable, instead, it passive wait the client side pull encoded data156 // by calling requestData API.157 mediaRecorder.start(3.6e+6);158 // Start recording. If timeSlice has been provided, mediaRecorder will159 // raise a dataavailable event containing the Blob of collected data on every timeSlice milliseconds.160 // If timeSlice isn't provided, UA should call the RequestData to obtain the Blob data, also set the mTimeSlice to zero.161 if (config.onAudioProcessStarted) {162 config.onAudioProcessStarted();163 }164 if (config.initCallback) {165 config.initCallback();166 }167 };168 /**169 * This method stops recording MediaStream.170 * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.171 * @method172 * @memberof MediaStreamRecorder173 * @example174 * recorder.stop(function(blob) {175 * video.src = URL.createObjectURL(blob);176 * });177 */178 this.stop = function(callback) {179 if (!mediaRecorder) {180 return;181 }182 this.recordingCallback = function(blob) {183 mediaRecorder = null;184 if (callback) {185 callback(blob);186 }187 };188 // mediaRecorder.state === 'recording' means that media recorder is associated with "session"189 // mediaRecorder.state === 'stopped' means that media recorder is detached from the "session" ... in this case; "session" will also be deleted.190 if (mediaRecorder.state === 'recording') {191 // "stop" method auto invokes "requestData"!192 // mediaRecorder.requestData();193 mediaRecorder.stop();194 }195 };196 /**197 * This method pauses the recording process.198 * @method199 * @memberof MediaStreamRecorder200 * @example201 * recorder.pause();202 */203 this.pause = function() {204 if (!mediaRecorder) {205 return;206 }207 if (mediaRecorder.state === 'recording') {208 mediaRecorder.pause();209 }210 };211 /**212 * This method resumes the recording process.213 * @method214 * @memberof MediaStreamRecorder215 * @example216 * recorder.resume();217 */218 this.resume = function() {219 if (this.dontFireOnDataAvailableEvent) {220 this.dontFireOnDataAvailableEvent = false;221 var disableLogs = config.disableLogs;222 config.disableLogs = true;223 this.record();224 config.disableLogs = disableLogs;225 return;226 }227 if (!mediaRecorder) {228 return;229 }230 if (mediaRecorder.state === 'paused') {231 mediaRecorder.resume();232 }233 };234 /**235 * This method resets currently recorded data.236 * @method237 * @memberof MediaStreamRecorder238 * @example239 * recorder.clearRecordedData();240 */241 this.clearRecordedData = function() {242 if (!mediaRecorder) {243 return;244 }245 this.pause();246 this.dontFireOnDataAvailableEvent = true;247 this.stop();248 };249 // Reference to "MediaRecorder" object250 var mediaRecorder;251 function isMediaStreamActive() {252 if ('active' in mediaStream) {253 if (!mediaStream.active) {254 return false;255 }256 } else if ('ended' in mediaStream) { // old hack257 if (mediaStream.ended) {258 return false;259 }260 }261 return true;262 }263 var self = this;264 // this method checks if media stream is stopped265 // or any track is ended.266 (function looper() {267 if (!mediaRecorder) {268 return;269 }270 if (isMediaStreamActive() === false) {271 if (!config.disableLogs) {272 console.log('MediaStream seems stopped.');273 }274 self.stop();275 return;276 }277 setTimeout(looper, 1000); // check every second278 })();279}280if (typeof RecordRTC !== 'undefined') {281 RecordRTC.MediaStreamRecorder = MediaStreamRecorder;...
test.spec.js
Source: test.spec.js
1/* eslint-disable prefer-promise-reject-errors */2const chai = require('chai');3const sandbox = require('sinon').createSandbox();4chai.use(require('chai-as-promised'));5const { expect } = chai;6const TestingEnvironment = require('../../src/index');7const testData = require('./test-data');8const Errors = require('../../src/errors');9const dockerFiles = {10 missing: 'missing.docker-compose.yml',11 working: 'test.docker-compose.yml',12 corrupt: 'corrupt.docker-compose.yml',13 noVerifications: 'no-verifications.docker-compose.yml',14 services: 'services.yml',15 mixed: 'mixed.yml',16};17const verificationTypes = { simple: { verificationFunction: () => {} }, missing: { property: true }, notFunctions: { verificationFunction: true } };18const verifications = { working: { postgres: verificationTypes.simple, node: verificationTypes.simple },19 notFunctions: { node: verificationTypes.notFunctions },20 missing: { postgres: verificationTypes.missing, node: verificationTypes.missing } };21describe('Testing missing parameters errors', () => {22 it('should throw missing parameter', () => {23 expect(() => {24 const test = new TestingEnvironment();25 }).to.throw();26 expect(() => {27 const test = new TestingEnvironment({ dockerComposeFileLocation: 2 });28 }).to.throw(Errors.MissingVariableError);29 expect(() => {30 const test = new TestingEnvironment({ dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });31 }).to.throw(Errors.MissingVariableError);32 expect(() => {33 const test = new TestingEnvironment({ verifications: 3 });34 }).to.throw(Errors.MissingVariableError);35 });36 it('should construct correctly', () => {37 expect(() => {38 const test = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });39 }).to.not.throw();40 });41 it('should get services', () => {42 const test = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });43 expect(test.services).to.deep.equal(testData.servicesJson);44 });45 it('should handel corrupt docker files', () => {46 expect(() => {47 const test = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.corrupt });48 }).to.throw(Errors.LoadingDockerComposeError);49 expect(() => {50 const test = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.missing });51 }).to.throw(Errors.MissingServicesInDockerComposeError);52 });53 it('should handel logEnabled', () => {54 const test = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: undefined });55 expect(test.disableLogs).to.be.false;56 test.disableLogs = true;57 expect(test.disableLogs).to.be.true;58 const test2 = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: false });59 expect(test2.disableLogs).to.be.false;60 const test3 = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: 23 });61 expect(test3.disableLogs).to.be.true;62 const test4 = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: 'test' });63 expect(test4.disableLogs).to.be.true;64 const test5 = new TestingEnvironment({ verifications: verifications.working, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: null });65 expect(test5.disableLogs).to.be.false;66 });67 it('should handel missing verifications', () => {68 expect(() => {69 const test = new TestingEnvironment({ verifications: verifications.missing, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: true });70 }).to.throw(Errors.MissingVerificationFunctionError);71 expect(() => {72 const test = new TestingEnvironment({ verifications: { node: verificationTypes.missing }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working, disableLogs: true });73 }).to.throw(Errors.MissingVerificationTypeError);74 });75});76describe('getService', () => {77 it('should handel missing service', () => {78 const test = new TestingEnvironment({ verifications: { ...verifications.working, node: { verificationFunction: 42 } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });79 expect(() => test.getService('nonExisting')).to.throw(Errors.MissingServiceError);80 });81 it('should get service', () => {82 const test = new TestingEnvironment({ verifications: { ...verifications.working, node: { verificationFunction: 42 } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });83 expect(test.getService('node-test')).to.deep.equal(testData.serviceJson['node-test']);84 });85});86describe('getVerificationFunction', () => {87 it('should handel missing verifications', () => {88 const test = new TestingEnvironment({ verifications: {}, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.noVerifications });89 expect(() => test.getVerificationFunction({ serviceName: 'test' })).to.throw(Errors.MissingVerificationError);90 });91 it('should handel missing service', () => {92 const test = new TestingEnvironment({ verifications: { ...verifications.working, node: { verificationFunction: 42 } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });93 expect(() => test.getVerificationFunction({ serviceName: 'test' })).to.throw(Errors.MissingServiceError);94 });95 it('should get verification promise', () => {96 const test = new TestingEnvironment({ verifications: { ...verifications.working, node: { verificationFunction: 42 } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.working });97 expect(test.getVerificationFunction({ serviceName: 'node-test' })).to.equal(42);98 });99});100const promiseRetryOptions = { retries: 0 };101describe('verifyServiceIsReady', () => {102 it('should handel no verifications services', async () => {103 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.resolve() } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.mixed, disableLogs: true });104 await test.verifyServiceIsReady({ serviceName: 'test' });105 await test.verifyServiceIsReady({ serviceName: 'test2' });106 });107 it('should reject a service that is down', async () => {108 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.reject('cant'), promiseRetryOptions } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.mixed, disableLogs: true });109 await expect(test.verifyServiceIsReady({ serviceName: 'test3' })).to.eventually.be.rejectedWith(Errors.CannotVerifyServiceIsUpError);110 });111 it('should wait for service', async () => {112 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.resolve() } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.mixed, disableLogs: true });113 await test.verifyServiceIsReady({ serviceName: 'test3' });114 });115});116describe('verifyAllServices', () => {117 it('should handel no verifications services', async () => {118 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.resolve() } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.mixed, disableLogs: true });119 await test.verifyAllServices();120 });121});122describe('buildServiceObjectFromJson', () => {123 it('should build services', async () => {124 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.resolve() } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.services, disableLogs: true });125 expect(test.getService('test')).to.deep.equal(testData.serviceJson.serviceTest1);126 });127 it('should build service with no ports', async () => {128 const test = new TestingEnvironment({ verifications: { httpServer: { verificationFunction: () => Promise.resolve() } }, dockerComposeFileLocation: __dirname, dockerFileName: dockerFiles.services, disableLogs: true });129 const service = test.getService('test3');130 delete service.ports[0].external;131 expect(service).to.deep.equal(testData.serviceJson.serviceTest2);132 });133});134describe('getActiveService', () => {...
smook.js
Source: smook.js
1import React from 'react';2import { log, useForceUpdate, getChangedModels } from './helpers';3// Smook -> State Management hOOK ð±4// Take ideas from:5// - https://github.com/reduxjs/react-redux/issues/11796// - https://github.com/reduxjs/react-redux/issues/1179#issuecomment-4761333007// Maybe use Proxies to improve perf?8// - https://github.com/dai-shi/reactive-react-redux9// - https://github.com/thekashey/proxyequal (no IE11 support!)10// Disable normal context update behaviour since we want to update11// the components manually via subscriptions12const calcChangedBits = () => 0;13const Context = React.createContext({}, calcChangedBits);14const EFFECT = 'EFFECT';15export const StoreProvider = ({ store, disableLogs, children }) => {16 const { rootReducer, initialState, models, setActions } = store;17 const [state, _dispatch] = React.useReducer(rootReducer, initialState);18 const currentState = React.useRef(state);19 const subscriptions = React.useRef({});20 // TODO: is there a better way to log prev + next state?21 // At the moment the next state is not logged in the same group...22 React.useEffect(() => {23 const changedModels = getChangedModels(currentState.current, state);24 if (changedModels.length > 0 && !disableLogs) {25 log.state(state, changedModels);26 }27 changedModels.forEach(m => {28 const affectedHandlers = subscriptions.current[m];29 affectedHandlers.forEach(handler => handler());30 });31 currentState.current = state; // Update ref to point in the current state32 }, [disableLogs, state]);33 const dispatch = React.useCallback(34 action => {35 if (!disableLogs) log.action(action, currentState.current);36 _dispatch(action);37 },38 [disableLogs]39 );40 const { actions, subscribe } = React.useMemo(() => {41 const subscribe = (modelName, handlerFn) => {42 if (!subscriptions.current[modelName]) {43 subscriptions.current[modelName] = [];44 }45 subscriptions.current[modelName].push(handlerFn);46 const unsubscribe = () => {47 const remaining = subscriptions.current[modelName].filter(48 x => x !== handlerFn49 );50 subscriptions.current[modelName] = remaining;51 };52 return unsubscribe;53 };54 const getState = () => currentState.current;55 const aggregated = Object.values(models).reduce((modelsAcc, model) => {56 const modelActions = Object.entries(model.actions).reduce(57 (actionsAcc, [actionName, value]) => {58 if (value.is === EFFECT) {59 actionsAcc[actionName] = (...args) => {60 dispatch({61 type: `${model.name}/${actionName}`,62 payload: args,63 });64 return value.fn(modelsAcc, getState, ...args);65 };66 } else {67 actionsAcc[actionName] = payload =>68 dispatch({69 type: `${model.name}/${actionName}`,70 payload,71 });72 }73 return actionsAcc;74 },75 {}76 );77 modelsAcc[model.name] = {78 actions: modelActions,79 selectors: model.selectors,80 };81 return modelsAcc;82 }, {});83 const actions = Object.entries(aggregated).reduce((acc, [key, val]) => {84 acc[key] = val.actions;85 return acc;86 }, {});87 // Make it possible to access actions directly from the store instance88 setActions(actions);89 return { actions, subscribe };90 }, [dispatch]); // eslint-disable-line91 return (92 <Context.Provider value={{ state, actions, models, subscribe }}>93 {children}94 </Context.Provider>95 );96};97export const useModel = name => {98 const { state, actions, models, subscribe } = React.useContext(Context);99 const forceUpdate = useForceUpdate();100 // NOTE: deps array can be empty since none of the used deps will not change101 React.useEffect(() => {102 const unsubscribe = subscribe(name, () => forceUpdate());103 return () => unsubscribe();104 }, []); // eslint-disable-line105 const select = fieldNameOrSelectorFn => {106 if (typeof fieldNameOrSelectorFn === 'string') {107 return state[name][fieldNameOrSelectorFn];108 } else {109 return fieldNameOrSelectorFn(state);110 }111 };112 return {113 select,114 actions: actions[name],115 selectors: models[name].selectors,116 };117};118export const createStore = models => {119 const initialState = models.reduce((acc, model) => {120 acc[model.name] = { ...model.state };121 return acc;122 }, {});123 const rootReducer = (state, action) => {124 const nextState = models.reduce((acc, model) => {125 acc[model.name] = model.reducer(state[model.name], action);126 return acc;127 }, {});128 return nextState || state;129 };130 const _models = models.reduce((acc, model) => {131 const reducerHandler = Object.entries(model.actions)132 .filter(([, fn]) => fn.is !== EFFECT)133 .reduce((acc, [name, fn]) => {134 acc[`${model.name}/${name}`] = fn;135 return acc;136 }, {});137 model.reducer = (state, action) =>138 reducerHandler[action.type]139 ? reducerHandler[action.type](state, action)140 : state;141 acc[model.name] = model;142 return acc;143 }, {});144 let _actions = null;145 const setActions = actions => {146 _actions = actions;147 };148 const getActions = () => {149 if (!_actions) {150 throw Error(151 'You need to render the Provider before accessing any actions from the instance store!'152 );153 }154 return _actions;155 };156 return {157 rootReducer,158 initialState,159 setActions,160 getActions,161 models: _models,162 };163};164export const effect = fn => ({ is: EFFECT, fn });165const fetchableReducer = field => (state, action) => ({166 ...state,167 [field]: { ...state[field], ...action.payload },168});169export const fetchable = {170 loading: () => ({ status: 'LOADING' }),171 failure: (error = '') => ({ error, status: 'FAILURE' }),172 success: (data = null) => ({ data, status: 'SUCCESS', error: null }),173 clear: () => ({ status: 'INITIAL', error: null }),174 value: initial => ({ data: initial, error: null, status: 'INITIAL' }),175 reducer: fetchableReducer,...
platform.js
Source: platform.js
1const persistentState = require('./helpers/persistentState')2const semver = require('semver');3if (semver.lt(process.version, '7.6.0')) throw new Error(`Homebridge plugins that use the "homebridge-platform-helper" library require your node version to be at least the v12.14.0 LTM. Current version: ${process.version}`)4class HomebridgePlatform {5 constructor (log, config = {}, homebridge) {6 this.log = log;7 this.config = config;8 this.homebridge = homebridge;9 const { homebridgeDirectory } = config;10 persistentState.init({ homebridge, homebridgeDirectory });11 }12 async addAccessories (accessories) {13 throw new Error('The addAccessories method must be overridden.')14 };15 async accessories (callback) {16 const { config, log } = this;17 const { name, disableLogs } = config;18 const accessories = [];19 await this.addAccessories(accessories);20 // Disable logs if requested21 if (disableLogs !== undefined) {22 accessories.forEach((accessory) => {23 if (accessory.config.disableLogs === undefined) {24 accessory.disableLogs = disableLogs25 }26 })27 }28 // Check for no accessories29 if (!config.accessories || config.accessories.length === 0) {30 if (!disableLogs) log(`No accessories have been added to the "${name}" platform config.`);31 return callback(accessories);32 }33 // Let accessories know about one-another if they wish34 accessories.forEach((accessory) => {35 if (accessory.updateAccessories) accessory.updateAccessories(accessories);36 })37 callback(accessories);38 }39}...
generalAccessories.test.js
Source: generalAccessories.test.js
1const { expect } = require('chai');2const { getAccessories } = require('./helpers/setup')3const log = () => {4 return null5}6// disableLogs7describe('disableLogs', () => {8 it('disableLogs true returns empty function', async () => {9 const config = {10 isUnitTest: true,11 hideScanFrequencyButton: true,12 disableLogs: true,13 hideLearnButton: true,14 accessories: [15 {16 name: 'Test',17 type: 'switch',18 disableLogs: true19 }20 ]21 };22 23 const accessories = await getAccessories(config, log);24 const logFunctionAsString = accessories[0].log.toString();25 const isEmptyFunction = logFunctionAsString === '() => {}';26 27 expect(isEmptyFunction).to.equal(true);28 });29 it('disableLogs false returns useful function', async () => {30 const config = {31 isUnitTest: true,32 hideScanFrequencyButton: true,33 hideLearnButton: true,34 accessories: [35 {36 name: 'Test',37 type: 'switch',38 }39 ]40 };41 const accessories = await getAccessories(config, log);42 43 const logFunctionAsString = accessories[0].log.toString();44 const isEmptyFunction = logFunctionAsString === '() => {}';45 expect(isEmptyFunction).to.equal(false);46 });...
learnAccessories.test.js
Source: learnAccessories.test.js
1const { expect } = require('chai');2const { getAccessories } = require('./helpers/setup')3describe('learnAccessories', () => {4 // // Empty Config5 it('empty config results in 2 accessories', async () => {6 const config = { disableLogs: true, isUnitTest: true };7 const accessories = await getAccessories(config);8 9 expect(accessories.length).to.equal(2);10 });11 12 // hideScanFrequencyButton13 it('hideScanFrequencyButton set to true in config results in 1 accessory', async () => {14 const config = { disableLogs: true, hideScanFrequencyButton: true, isUnitTest: true };15 const accessories = await getAccessories(config);16 17 expect(accessories.length).to.equal(1);18 });19 // hideLearnButton20 it('hideLearnButton set to true in config results in 1 accessory', async () => {21 const config = { disableLogs: true, hideLearnButton: true, isUnitTest: true };22 const accessories = await getAccessories(config);23 24 expect(accessories.length).to.equal(1);25 });...
Using AI Code Generation
1const { disableLogs } = require('playwright/lib/utils/debug');2disableLogs();3const { disableLogs } = require('playwright/lib/utils/debug');4disableLogs();5const { disableLogs } = require('playwright/lib/utils/debug');6disableLogs();7const { disableLogs } = require('playwright/lib/utils/debug');8disableLogs();9const { disableLogs } = require('playwright/lib/utils/debug');10disableLogs();11const { disableLogs } = require('playwright/lib/utils/debug');12disableLogs();13const { disableLogs } = require('playwright/lib/utils/debug');14disableLogs();15const { disableLogs } = require('playwright/lib/utils/debug');16disableLogs();17const { disableLogs } = require('playwright/lib/utils/debug');18disableLogs();19const { disableLogs } = require('playwright/lib/utils/debug');20disableLogs();21const { disableLogs } = require('playwright/lib/utils/debug');22disableLogs();23const { disableLogs } = require('playwright/lib/utils/debug');24disableLogs();25const { disableLogs } = require('playwright/lib/utils/debug');26disableLogs();27const { disableLogs } = require('playwright/lib/utils/debug');28disableLogs();29const { disableLogs } = require('playwright/lib/utils/debug');30disableLogs();31const { disableLogs } = require('playwright/lib/utils/debug');32disableLogs();33const { disableLogs } = require('playwright/lib/utils/debug');34disableLogs();
Using AI Code Generation
1const { disableLogs } = require('playwright/lib/server/trace/recorder');2disableLogs();3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const page = await browser.newPage();7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();
Using AI Code Generation
1const {chromium} = require('playwright');2const {InternalLogger} = require('playwright/lib/utils/logger');3InternalLogger.disableLogs();4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();
Using AI Code Generation
1const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");2PlaywrightInternal.disableLogs();3const { Playwright } = require("@playwright/test");4Playwright.disableLogs();5const { Playwright } = require("@playwright/test");6const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");7PlaywrightInternal.disableLogs();8const { Playwright } = require("@playwright/test");9const { PlaywrightInternal } = Playwright;10PlaywrightInternal.disableLogs();11const { Playwright } = require("@playwright/test");12const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");13const { PlaywrightInternal } = Playwright;14PlaywrightInternal.disableLogs();15const { Playwright } = require("@playwright/test");16const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");17const { PlaywrightInternal } = Playwright;18PlaywrightInternal.disableLogs();19const { Playwright } = require("@playwright/test");20const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");21const { PlaywrightInternal } = Playwright;22PlaywrightInternal.disableLogs();23const { Playwright } = require("@playwright/test");24const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");25const { PlaywrightInternal } = Playwright;26PlaywrightInternal.disableLogs();27const { Playwright } = require("@playwright/test");28const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");29const { PlaywrightInternal } = Playwright;30PlaywrightInternal.disableLogs();31const { Playwright } = require("@playwright/test");32const { PlaywrightInternal } = require("@playwright/test/lib/server/playwright");33const { PlaywrightInternal } = Playwright;34PlaywrightInternal.disableLogs();35const { Playwright
Using AI Code Generation
1const { InternalLogger } = require('playwright/lib/utils/logger');2InternalLogger.disableLogs();3const { chromium } = require('playwright');4const { Logger } = require('playwright/lib/utils/logger');5Logger.disableLogs();6const { chromium } = require('playwright');7const { chromium } = require('playwright');8const context = await chromium.launch().newContext();9context.disableLogs();10await context.close();11const { chromium } = require('playwright');12const browser = await chromium.launch();13browser.disableLogs();14await browser.close();15const { chromium } = require('playwright');16const browser = await chromium.launch();17const page = await browser.newPage();18page.disableLogs();19await browser.close();20const { chromium } = require('playwright');21chromium.disableLogs();22await chromium.launch();23const { chromium } = require('playwright');24const browserServer = await chromium.launchServer();25browserServer.disableLogs();26await browserServer.close();27const { chromium } = require('playwright');28const browserFetcher = chromium.createBrowserFetcher();29browserFetcher.disableLogs();30await browserFetcher.download('123456');31const { chromium } = require('playwright');32const context = await chromium.launch().newContext();33context.disableLogs();34await context.close();35const { chromium } = require('playwright');36const context = await chromium.launch().newContext();37context.disableLogs();38await context.close();39const { chromium } = require('playwright');40const context = await chromium.launch().newContext();41context.disableLogs();42await context.close();43const { chromium } = require('playwright');44const context = await chromium.launch().newContext();45context.disableLogs();46await context.close();47const { chromium } = require('playwright');
Using AI Code Generation
1const { disableLogs } = require('@playwright/test/lib/utils/debug');2disableLogs();3const { disableLogs } = require('@playwright/test');4disableLogs();5disableLogs()6const { disableLogs } = require('@playwright/test');7disableLogs();8const { disableLogs } = require('@playwright/test/lib/utils/debug');9disableLogs();10disableLogs()11const { disableLogs } = require('@playwright/test');12disableLogs();13const { disableLogs } = require('@playwright/test/lib/utils/debug');14disableLogs();15disableLogs()16const { disableLogs } = require('@playwright/test');17disableLogs();18const { disableLogs } = require('@playwright/test/lib/utils/debug');19disableLogs();20disableLogs()21const { disableLogs } = require('@playwright/test');22disableLogs();23const { disableLogs } = require('@playwright/test/lib/utils/debug');24disableLogs();25disableLogs()26const { disableLogs } = require('@playwright/test');27disableLogs();28const { disableLogs } = require('@playwright/test/lib/utils/debug');29disableLogs();
Using AI Code Generation
1const { disableLogs } = require('@playwright/test/lib/utils/logger');2disableLogs();3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await browser.close();9})();10const { chromium } = require('@playwright/test/lib/server/chromium');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await browser.close();16})();17const { chromium } = require('@playwright/test/lib/server/chromium/experimental');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await browser.close();23})();24const { chromium } = require('@playwright/test/lib/server/chromium/experimental');25(async () => {26 const browser = await chromium.launch();27 const context = await browser.newContext();28 const page = await context.newPage();29 await browser.close();30})();31const { chromium } = require('@playwright/test/lib/server/chromium/experimental');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 await browser.close();37})();38const { chromium } = require('@playwright/test/lib/server/chromium/experimental');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await browser.close();44})();45const { chromium } = require('@playwright/test
Using AI Code Generation
1const { disableLogs } = require('@playwright/test/lib/utils/debug');2disableLogs();3const { disableLogs } = require('@playwright/test/lib/utils/debug');4disableLogs();5const { disableLogs } = require('@playwright/test/lib/utils/debug');6disableLogs();7const { disableLogs } = require('@playwright/test/lib/utils/debug');8disableLogs();9const { disableLogs } = require('@playwright/test/lib/utils/debug');10disableLogs();11const { disableLogs } = require('@playwright/test/lib/utils/debug');12disableLogs();13const { disableLogs } = require('@playwright/test/lib/utils/debug');14disableLogs();15const { disableLogs } = require('@playwright/test/lib/utils/debug');16disableLogs();17const { disableLogs } = require('@playwright/test/lib/utils/debug');18disableLogs();19const { disableLogs } = require('@playwright/test/lib/utils/debug');20disableLogs();21const { disableLogs } = require('@playwright/test/lib/utils/debug');22disableLogs();23const { disableLogs } = require('@playwright/test/lib/utils/debug');24disableLogs();25const { disableLogs } = require('@playwright/test/lib/utils/debug');26disableLogs();
Using AI Code Generation
1const { disableLogs } = require('playwright/lib/utils/debug');2disableLogs();3const { disableLogs } = require('playwright');4disableLogs();5const { disableLogs } = require('playwright/lib/utils/debug');6disableLogs('chromium');7const { disableLogs } = require('playwright');8disableLogs('chromium');9const { disableLogs } = require('playwright/lib/utils/debug');10disableLogs('all');11const { disableLogs } = require('playwright');12disableLogs('all');13const { disableLogs } = require('playwright/lib/utils/debug');14disableLogs('chromium');15disableLogs('all');16const { disableLogs } = require('playwright');17disableLogs('chromium');18disableLogs('all');19const { enableLogs } = require('playwright/lib/utils/debug');20enableLogs('chromium');21enableLogs('all');22const { enableLogs } = require('playwright');23enableLogs('chromium');24enableLogs('all');25const { enableLogs } = require('playwright/lib/utils/debug');26enableLogs('chromium');27const { enableLogs } = require('playwright');28enableLogs('chromium');29const { enableLogs } = require('playwright/lib/utils/debug');30enableLogs('all');31const { enableLogs } = require('playwright');32enableLogs('
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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.
Get 100 minutes of automation test minutes FREE!!