Best JavaScript code snippet using playwright-internal
handlers.js
Source:handlers.js  
1var AnSWFUInstance; // å
¨å±çSWFUå®ä¾2/**3 * ä¸ä¼ é误æç¤ºä¿¡æ¯4 */5var uploadErrorMsg = {6	'show' : function(msg){7		$("#wuQError").append(msg).show();8		return this;9	},10	'hide' : function(){11		$("#wuQError").hide("slow").text("");12		return this;13	}14};15/**16 * AnSWFUHandlers SWFUä¸ä¼ çå¤çæ¹æ³17 */18var AnSWFUHandlers = {19	swfUploadLoaded : function () {20      swfUploadLoaded(this);21	},22	fileDialogStart : function() {23	  uploadErrorMsg.hide();24	},25	26	fileQueueError : function (file, errorCode, message) {27		try {28			var errorName = "";29			switch (errorCode) {30			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:31				errorName = "ä¸ä¼ ç
§ç䏿¬¡ä¸è½è¶
è¿"+AnSWFUInstance.settings.file_upload_limit+"å¼ ï¼è¯·éæ°éæ©ã";32				break;33			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:34				errorName = "ç
§ç大å°ä¸è½è¶
è¿2Mï¼è¯·éæ°ä¸ä¼ "+file.name;35				break;36			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:37				errorName = file.name+"ç大å°ä¸º0åèï¼æ æ³ä¸ä¼ ï¼è¯·éæ©å
¶ä»æä»¶ã";38				break;39			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:40				errorName = file.name+"为ä¸å
许çæä»¶ç±»åï¼æ æ³ä¸ä¼ ï¼è¯·éæ©å
¶ä»æä»¶ã";41				break;42			default:43				errorName = "æªç¥é误ï¼è¯·éæ°éæ©ã";44				break;45			}46			uploadErrorMsg.show(errorName);47		} catch (ex) {48			this.debug(ex);49		}50	},51	52	fileQueued : function (file) {53		try {54			// æ¾ç¤ºéåæ°æ®55			queueData(file);56		} catch (ex) {57			this.debug(ex);58		}59	},60	fileDialogComplete : function (numFilesSelected, numFilesQueued) {61		try {62			// éèé误信æ¯63			if (numFilesSelected == numFilesQueued) uploadErrorMsg.hide();64		} catch (ex) {65			this.debug(ex);66		}67	},68	uploadStart : function (file) {69		try {70			// ä¸ä¼ å°è¯¥æä»¶æ¶ï¼éè该æä»¶çå é¤æé®71			$("a.delete", $("#"+file.id)).hide();72		} catch (ex) {73			this.debug(ex);74		}75		return true;76	},77	uploadProgress : function (file, bytesLoaded, totalBytes) {78		try {79			queuePercent = Math.ceil(bytesLoaded / totalBytes * 100);80			$(".progressBar div", $("#"+file.id)).text(queuePercent+'%').css("width", queuePercent+"%");81			if (queuePercent == 100) {82				$(".progressBar div", $("#"+file.id)).text('ä¸ä¼ å®æ¯ã');83			}84		} catch (ex) {85			this.debug(ex);86		}87	},88	uploadSuccess : function (file, serverData, receivedResponse) {89		try {90			//@TODO ä¸ä¼ æåï¼è¿åæ°æ®çæä½ å¤çå°é¢91			var attachmentInfo = serverData.split("|");92			var attachmentId = attachmentInfo[0];93			var attachmentPath = attachmentInfo[1];94			// éèçéä»¶ID95			$("#"+file.id).append('<input type="hidden" name="attachments[]" value="'+attachmentId+'" />');96			var newKey = parseInt($("#"+file.id).find(".viewOrder").val());97			$("#"+file.id).append('<input type="hidden" name="view_keys[]" value="'+ newKey +'" />');98			// coverçå¼99			$("input[type=radio]", $("#"+file.id)).val(attachmentPath);100		} catch (ex) {101			uploadErrorMsg.show('ä¸ä¼ é误ï¼è¯·å·æ°é¡µé¢éè¯ä¸ä¼ ï¼');102			this.debug(ex);103		}104	},105	uploadError : function (file, errorCode, message) {106		try {107			var errorName = "";108			switch (errorCode) {109			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:110				errorName = "HTTP ERROR";111				break;112			case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:113				errorName = "MISSING UPLOAD URL";114				break;115			case SWFUpload.UPLOAD_ERROR.IO_ERROR:116				errorName = "IO ERROR";117				break;118			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:119				errorName = "SECURITY ERROR";120				break;121			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:122				errorName = "UPLOAD LIMIT EXCEEDED";123				break;124			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:125				errorName = "UPLOAD FAILED";126				break;127			case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:128				errorName = "SPECIFIED FILE ID NOT FOUND";129				break;130			case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:131				errorName = "FILE VALIDATION FAILED";132				break;133			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:134				//errorName = "FILE CANCELLED";135				return;136				break;137			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:138				errorName = "FILE STOPPED";139				break;140			default:141				errorName = "ä¸ä¼ é误ï¼è¯·å·æ°é¡µé¢éè¯ä¸ä¼ ï¼";142				break;143			}144			errorName += '<br />';145			uploadErrorMsg.show('ä¸ä¼ é误ï¼è¯·å·æ°é¡µé¢éè¯ä¸ä¼ ï¼');146			// æ¾ç¤ºæµè§æé®147			AnSWFUInstance.setButtonDisabled(false);148			// æ¾ç¤ºæ¸
空æé®149			$("#btnClear").removeClass('btnClear').attr('disabled', '');150			// æ¾ç¤ºå é¤æé®151			$("a.delete", $("#"+file.id)).show();152			// 使ä¿åæé®çæ153			$(':submit').val('æ´æ°').attr('disabled', '');154		} catch (ex) {155			this.debug(ex);156		}157	},158	uploadComplete : function (file) {159		return true;160	},161	// @require plugins/swfupload.queue.js162	queueComplete : function (file) {163		try {164			//this.debug(queuePercent);165			if (AnSWFUInstance.getStats().files_queued === 0) {166				// çå¾
å¾çä¸ä¼ å®æ¯åæäº¤è¡¨å167				$(':submit').val("å¤çæ°æ®ä¸");168				$("form").submit();169				return false;170			} else {171				this.debug(queueBytesLoaded+'/'+'queueBytes');172				// åçéè¯¯ï¼æ¾ç¤ºæ¸
空æé®173				$("#btnClear").show();174			}175		} catch (ex) {176			this.debug(ex);177		}178	},179	// This custom debug method sends all debug messages to the Firebug console.  If debug is enabled it then sends the debug messages180	// to the built in debug console.  Only JavaScript message are sent to the Firebug console when debug is disabled (SWFUpload won't send the messages181	// when debug is disabled).182	debug : function (message) {183		try {184			if (window.console && typeofwindow.console.error === "function" && typeofwindow.console.log === "function") {185				if (typeofmessage === "object" && typeofmessage.name === "string" && typeofmessage.message === "string") {186					window.console.error(message);187				} else {188					window.console.log(message);189				}190			}191		} catch (ex) {192		}193		try {194			if (this.settings.debug) {195				this.debugMessage(message);196			}197		} catch (ex1) {198		}199	}200};201/**202 * swfuploadåå§åæä½203 * @param swfuInstance204 * @return205 */206function swfUploadLoaded(swfuInstance){207	// å
¨å±å®ä¾208	AnSWFUInstance = swfuInstance;209	$("form").submit(function(e){210		// å¦æè¡¨åéªè¯ä¸éè¿ ä¸è½æäº¤ åvalidateç»ä¸211		if(!$("form").valid()) {212          return false;213		}214        // 夿éå䏿¯å¦æä¸ä¼ æä»¶215		var statsObj = AnSWFUInstance.getStats();216		if (statsObj.files_queued != 0) {217			// å±è½æµè§å¨é»è®¤è¡ä¸º218	        e.preventDefault();219	        // 设置æµè§æé®disabled220	        AnSWFUInstance.setButtonDisabled(true);221			// 设置æ¸
空æé®å¤±æ222			$("#btnClear").addClass('btnClear').attr('disabled', 'disabled');223			// å±è½æä¿åæé®224			$(':submit').val('ä¸ä¼ ä¸...').attr('disabled', 'disabled');225			// å¼å§ä¸ä¼ 226	        try {227	          AnSWFUInstance.startUpload();228	        } catch (ex) {229	      230	        }231	        return false;232		}233	});234	// æ¸
空235	$('#btnClear').click(function(){236		// 夿é忝妿£å¨ä¸ä¼ 237		var statsObj = AnSWFUInstance.getStats();238		if (statsObj.in_progress == 1) {239			uploadErrorMsg.show('æä»¶æ£å¨ä¸ä¼ ä¸ï¼æ æ³æ¸
空');240			return false;241		}242		// é置计æ°243		//queueBytes = 0;244		//queueItem.reset().show();245		// ä»flashåéä¸ç§»é¤246		// @require plugins/swfupload.queue.js247		AnSWFUInstance.cancelQueue();248		// ä»htmléåä¸ç§»é¤249		$("tr", $('#uploaderQueue table')).slideUp('fast', function(){250			$(this).remove();251		});252	});253}254/**255 * æ¾ç¤ºéåæ°æ®256 * @param fileData257 * @return258 */259function queueData(fileData, isDefault){260	// çæéåhtml代ç 261	var queueHtml = queueHtmlGenerator(fileData, isDefault);262	// å°htmlä»£ç æå
¥å°éåä¸263	var _elem = $(queueHtml);264	$('#uploaderQueue table').append(_elem);265	// ç»å®å é¤äºä»¶266	$('a.delete', _elem).click(function(){267		$(this).closest('tbody').slideUp("fast", function(){268			$(this).remove();269		});270		AnSWFUInstance.cancelUpload(fileData.id);271	});272	_elem = null;273}274/**275 * çæåéhtml代ç 276 * @param fileData277 * @return278 * @require plugins/swfupload.speed.js for SWFUpload.speed.formatSize()279 */280var insertIndex = 1;281function queueHtmlGenerator(fileData, isDefault){282	283	// ä»flashéæ©çæä»¶fileData䏿¯æ²¡ætitleï¼introåpath屿§çï¼åªæé»è®¤æ°æ®ææ284	if (fileData.title == undefined) fileData.title = '';285	if (fileData.intro == undefined) fileData.intro = '';286	if (fileData.path == undefined) fileData.path = '';287	if (fileData.cover == undefined) fileData.cover = '';288	if (fileData.extension == undefined) fileData.extension = '';289	if (fileData.description == undefined) fileData.description = '';290	var queueHtml = '';291	viewOrder++;292	queueHtml += '<tbody class="wuI"><tr id="'+fileData.id+'">';293	queueHtml += '<td class="u-name">'+fileData.name+'</td>';294	queueHtml += '<td class="u-size"><input style="display:none;" type="radio" name="cover" value="'+fileData.path+'"';295	if ((!isDefault &&insertIndex == 1) || (isDefault && fileData.cover == fileData.path)) {296      //queueHtml += 'checked="checked"';297	}298	//queueHtml += '/>设为å°é¢</td>';299	queueHtml += '/></td>';300	301	queueHtml += '<td class="u-size">'+SWFUpload.speed.formatBytes(fileData.size)+'</td>';302	queueHtml += '<td class="progressBar" width="200px"><div style="background:blue;"></div></td>';303	queueHtml += '<td class="u-option"><a href="javascript:void(0);" class="delete">å é¤</a></td>';304	queueHtml += '<input class="oldViewOrder" type="hidden" value="'+viewOrder+'" name="default_view_order['+fileData.id+']">';305	queueHtml += '<input class="viewOrder" type="hidden" value="'+viewOrder+'" name="view_order[]" />';306	// é»è®¤æ°æ® nameä¸ä¸éè¦_indexï¼åå°ådiff307	if (isDefault) queueHtml += '<input type="hidden" name="default_attachments[]" value="'+fileData.id+'" />';308	queueHtml += '</tr>';309	if (isDefault) {310	  queueHtml += '<tr><td>æè¿°ï¼</td><td colspan="4"><textarea name="default_description['+fileData.id+']">';311	} else {312	  queueHtml += '<tr><td>æè¿°ï¼</td><td colspan="4"><textarea name="description[]">';313	}314	if (fileData.description) {315	  queueHtml += fileData.description;316	}317	queueHtml += '</textarea></td></tr></tbody>';318	insertIndex++;319	return queueHtml;...DTGUI-main.js
Source:DTGUI-main.js  
1let fs = require('fs');2let getAppDataPath = require("appdata-path");3let DTWrapper = require("./DTWrapper.js");4let DTCmd = require('./DTCmd.js');5const {6    ipcMain, app7} = require('electron');8//const owpath = "C:/Program Files (x86)/Overwatch/_retail_";9const owpath = require('./settings.js').settings.owpath.path;10const dtpath = getAppDataPath("Yernemm/OWET2/datatool");11const outpath = getAppDataPath("Yernemm/OWET2/output/extracted");12const logFile = getAppDataPath("Yernemm/OWET2/output/logs") + `/log-${new Date().getTime()}.txt`;13const DTData = require('./DTData.js');14const DTUpdater = require('./DTUpdater.js');15console.log("ummm sonny");16///17var logStream;18logStream = fs.createWriteStream(logFile, {19    flags: 'a'20});21let dt;22ipcMain.on('runConsoleCmd', (event, args) => {23    dt.addToQueue(args.cmd, args.flags, args.args);24    dt.runQueue();25    event.sender.send('updateQueue', {26        data: queueHtml()27    });28});29ipcMain.on('DtOpenCurrentLog', (event, args)=>{30    let notepadCmd = require('child_process').spawn;31    notepadCmd('C:\\windows\\notepad.exe', [logFile]);32});33ipcMain.on('DtOpenOutputFolder', (event, args)=>{34    require('child_process')35    .exec(`start "" "${getAppDataPath("Yernemm/OWET2/output")}"`);36});37ipcMain.on('DTLoaded', (event, args) => {38    let dtu = new DTUpdater();39    dtu.update().then(() => {40        console.log("DT Loaded");41        dt = new DTWrapper(dtpath, owpath, outpath, (data) => {42            event.sender.send('updateConsole', {43                data: data44            });45            logStream.write(data);46        }, (o) => {47            event.sender.send('updateConsole', {48                data: `\n[OWET] Exited with code ${o.code}\n\n`49            });50            logStream.write(`\n[OWET] Exited with code ${o.code}\n\n`);51            event.sender.send('updateQueue', {52                data: queueHtml()53            });54        });55        let dtd = new DTData(dtpath, owpath);56        dtd.getInfo().then(json => {57            sendbtns({Keyword: 'help', Description: 'Help'});58            ['DumpFlags', 'ListFlags', 'ExtractFlags', 'ExtractMapEnvFlags']59            .forEach(item => {60                json.ToolGroups[item].Tools.forEach(tool => sendbtns(tool));61            })62            function sendbtns(tool) {63                event.sender.send('addBtn', {64                    cmd: tool.Keyword,65                    text: tool.Description66                });67            }68        });69    })70    .catch(err=>console.log("ERROR\n" + err));71});72ipcMain.on('removeQueue', (event, args) => {73    dt.removeFromQueue(args.id);74    event.sender.send('updateQueue', {75        data: queueHtml()76    });77});78function queueHtml() {79    let h = "";80    dt.cmdQueue.forEach((cmd, id) => {81        if (id == 0) {82            h += `<p>Running</p>`;83        }84        if (id == 1) {85            h += `<p>Queue</p>`;86        }87        h +=88            `       <div class='buttonContainerStatic buttonContainerQueue tooltip'>89                    <a class='button' onClick="removeQueue(${id})">${cmd.cmdName} ${cmd.args}</a>90                    <span class="tooltiptext">${cmd.cmd.split('& ')[1]}</span>91                </div>  92        `;93    });94    return h;95}96let SettingsManager = require('./SettingsManager.js');97let sm = new SettingsManager();98console.log(JSON.stringify(sm.createDefaults()));99ipcMain.on('settingsSave', (event, args)=>{100    sm.saveSettings(args)101    .then(()=>event.sender.send('settingsSaved', 'Settings saved. Restart OWET 2 to apply.'))102    .catch((err)=>event.sender.send('settingsSaved', err));103    104});105const packageJson = require('./../../package.json');106console.log(packageJson.version);107ipcMain.on('mainMenuLoaded', (event, args)=>{108    console.log('e')109    event.sender.send('mainMenuSetVersion', packageJson.version)   110});111function runAtMain() {112}113//logStream.end();114ipcMain.on('ClearCache', (event, args) => { 115    116    try {117        fs.unlinkSync(getAppDataPath("Yernemm/OWET2/cache/toolinfo.json"));118    } catch (error) {119        120    }121    try {122        fs.unlinkSync(getAppDataPath("Yernemm/OWET2/cache/toolinfoChoices.json"));123    } catch (error) {124        125    }126    app.relaunch();127    app.exit();128 });129module.exports = {130    runAtMain...main.js
Source:main.js  
1"use strict";2/**3 * File Name: main.js4 * Description: This JavaScript file is meant to be read by index.html5 *              Defines the functions required to:6 *                  display the current queue and the clock, 7 *                  remove a student from a queue, 8 *                  and view a student's information.9 */10// Task 711/**12 * Function Name: checkDigits13 * @desc Converts a 1 digit number to 2 digits by adding a zero to the left.14 * @param {string} digits number to be checked15 * @return 2 digit number (as a string)16 */17function checkDigits(digits) {18    if (digits < 10) {19        digits = "0" + digits;20    }21    return digits;22}23/**24 * Function Name: updateClock25 * @desc Updates the time for the clock in index.html26 */27function updateClock() {28    let timeRef = document.getElementById("currentTime");29    let today = new Date();30    let hours = checkDigits(today.getHours());31    let minutes = checkDigits(today.getMinutes());32    let seconds = checkDigits(today.getSeconds());33    let time = hours + ":" + minutes + ":" + seconds;34    timeRef.innerText = time;35}36// Task 837/**38 * Function Name: view39 * @desc Saves student's position in queue and queue number to localStorage, then redirects to view.html40 * @param {number} index student's position in queue41 * @param {number} queueIndex queue number42 */43function view(index, queueIndex) {44    localStorageUpdate(STUDENT_INDEX_KEY, index);45    localStorageUpdate(STUDENT_QUEUE_KEY, queueIndex);46    window.location.href = "view.html";47}48// Task 949/**50 * Function Name: markDone51 * @desc Confirm with the user that they want to mark student as done, then removes student from queue.52 * @param {number} index student's position in queue53 * @param {number} queueIndex queue number54 */55function markDone(index, queueIndex) {56    let confirmation = confirm("Mark student as done?");57    if (confirmation == true) {58        consultSession.removeStudent(index, queueIndex);59        localStorageUpdate(APP_DATA_KEY, consultSession)60    }61    displayQueue(consultSession.queue)62}63// Task 1064// display the current queue status to the user65/**66 * Function Name: displayQueue67 * @desc display the current queue status to the user in index.html68 * @param {Session} data the Session class instance associated with APP_DATA_KEY in localStorage69 */70function displayQueue(data) {71    let completeHTML = "";72    let queueHTML = "";73    let queueNumber = 0;74    let queueContent = document.getElementById("queueContent");75    for (let i = 0; i < data.length; i++) {76        for (let j = 0; j < data[i].length; j++) {77            let fullName = data[i][j].fullName78            queueHTML = `79                ${queueHTML}80                <li class="mdl-list__item mdl-list__item--three-line">81                    <span class="mdl-list__item-primary-content">82                        <i class="material-icons mdl-list__item-avatar">person</i>83                        <span>${fullName}</span>84                    </span>85                    <span class="mdl-list__item-secondary-content">86                        <a class="mdl-list__item-secondary-action" onclick="view(${j},${i})"><i87                            class="material-icons">info</i></a>88                    </span>89                    <span class="mdl-list__item-secondary-content">90                        <a class="mdl-list__item-secondary-action" onclick="markDone(${j},${i})"><i91                            class="material-icons">done</i></a>92                    </span>93                </li>94            `;95        }96        queueNumber = i + 1;97        completeHTML = `98            ${completeHTML}99            <ul class="mdl-list">100                <h4>Queue ${queueNumber}</h4>101                ${queueHTML}102            </ul>103        `;104        queueHTML = "";105    }106    queueContent.innerHTML = completeHTML;107}108updateClock();109setInterval(updateClock, 1000);...queue-view.js
Source:queue-view.js  
1// native2var EventEmitter = require('events').EventEmitter3var inherits = require('util').inherits4//3rd party5var Mustache = require('mustache')6module.exports = QueueView7function QueueView (model, config) {8  this.model = model9  this.itemTemplate = $(config.itemTemplate).html()10  this.queueSelector = config.songQueue11  this.DOM = {12    songQueue: config.songQueue,13    $songQueue: $(this.queueSelector)14  }15  // speeds up future renders16  Mustache.parse(this.itemTemplate)17  // init Dragula in queue18  // TODO: prevent top song from being dragged if DJ19  /*20  var drake = dragula([document.querySelector(this.queueSelector)])21  // save queue when reordered22  drake.on('drop', function (el, target, source, sibling) {23    this.emit('reorder', el, sibling)24  })25  */26  27}28inherits(QueueView, EventEmitter)29QueueView.prototype.render = function () {30  var self = this31  var songs = this.model.getSongs()32  var template = this.itemTemplate33  var queueHTML = ''34  songs.forEach(function (song) {35    var params = {36      title: song.title,37      source: song.source,38      id: song.id,39      duration: song.duration,40      prettyDuration: self._prettyDuration(song.duration)41    }42    queueHTML += Mustache.render(template, params)43  })44  this.DOM.$songQueue.html(queueHTML)45}46QueueView.prototype.cycle = function () {47  this.DOM.$songQueue.find('li').first().detach().appendTo(this.DOM.$songQueue)48}49QueueView.prototype.appendSong = function (song) {50  var self = this51  var template = this.itemTemplate52  var params = {53    title: song.title,54    source: song.source,55    id: song.id,56    duration: song.duration,57    prettyDuration: this._prettyDuration(song.duration)58  }59  var $renderedSong = $(Mustache.render(template, params))60  this.DOM.$songQueue.append($renderedSong)61}62QueueView.prototype.removeSong = function (index) {63  this._songAtIndex(index).remove()64}65QueueView.prototype.moveToTop = function (index) {66  var $song = this._songAtIndex(index).detach()67  this.DOM.$songQueue.prepend($song)68}69//TODO: pad numbers with 0's70QueueView.prototype._prettyDuration = function (duration) {71  var momentDuration =  moment.duration(duration, 'seconds')72  var seconds = momentDuration.seconds()73  var minutes = momentDuration.minutes()74  var hours = momentDuration.hours()75  seconds = ('0' + seconds).slice(-2)76  var pretty = minutes + ':' + seconds77  if (hours > 0) {78    hours = ('0' + hours).slice(-2)79    pretty = hours + ':' + pretty80  }81  return pretty82}83QueueView.prototype._songAtIndex = function (index) {84  return this.DOM.$songQueue.children().eq(index)...DOMLazyTree.js
Source:DOMLazyTree.js  
...59  } else {60    parentTree.node.appendChild(childTree.node);61  }62}63function queueHTML(tree, html) {64  if (enableLazy) {65    tree.html = html;66  } else {67    tree.node.innerHTML = html;68  }69}70function queueText(tree, text) {71  if (enableLazy) {72    tree.text = text;73  } else {74    setTextContent(tree.node, text);75  }76}77function DOMLazyTree(node) {...index.js
Source:index.js  
1var last;2function getStatus(callback) {3  $.ajax("/status").done(function(data) {4    callback(data);5  }).fail(function() {6    callback();7  });8}9function update() {10  getStatus(function(data) {11    console.log(data);12    // Check if the data is new13    if (!data) {14      return setTimeout(update, 1000);    15    } else if (data.updated || !last) {16      // Status set17      if (data.status) {18        if (data.status == "play") {19          $("#status").removeClass("glyphicon-pause");20          $("#status").addClass("glyphicon-play");21        } else {22          $("#status").removeClass("glyphicon-play");23          $("#status").addClass("glyphicon-pause");24        }25      }26      // Current track set27      if (data.current) {28        $("#track").html(data.current.name);29        if (data.current.artwork) {30          $("#albumart").attr("src","data:image/png;base64," + data.current.artwork);31          $("#background").css("background-image","url(data:image/png;base64," + data.current.artwork + ")");32        }33        if (data.current.artists.length > 0) {34          $("#artist").html(data.current.artists[0].name);35        }36      }37      // Queue data set38      if (data.queue && data.queue.length > 0) {39        var queueHtml = "";40        $.each(data.queue, function(i, track) {41          if (track) {42            queueHtml += "<div class='queueTrack info'>" + track.name + " by " + track.artist + "</div>";43          } else {44            queueHtml += "<div class='queueTrack info'>Loading...</div>";45          }46        });47        $("#queue").html(queueHtml);48      } else {49        $("#queue").html("");50      }51    }52    setTimeout(update, 1000);    53    last = data;54  });55}56$(document).ready(function() {57  update();...queue.js
Source:queue.js  
1let queueForm = document.forms.queueForm;2let ol = document.createElement("ol");3ol.innerHTML = localStorage.queueHTML || null;4document.body.append(ol);5queueForm.elements.addButton.onclick = function () {6    if (ol.children.length < 19 && queueForm.elements.queueValue.value) {7        ol.innerHTML += `<li>${queueForm.elements.queueValue.value}</li>`;8        localStorage.setItem("queueHTML", ol.innerHTML);9        queueForm.elements.queueValue.value = "";10    } else {11        alert("queue is full or you entered an invalid value");12    }13};14queueForm.elements.removeButton.onclick = function () {15    if (!ol.children.length) {16        delete localStorage.queueHTML;17        alert("queue is empty");18    } else {19        ol.children[0].remove();20        localStorage.setItem("queueHTML", ol.innerHTML);21    }22};23queueForm.onsubmit = function () {24    return false;...Using AI Code Generation
1const { queueHTML } = require('@playwright/test');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 page.click('text=Get started');8  const html = await queueHTML(page);9  console.log(html);10  await browser.close();11})();Using AI Code Generation
1const playwright = require('playwright');2const { queueHTML } = require('playwright-internal');3(async () => {4  const browser = await playwright.chromium.launch();5  const page = await browser.newPage();6  const html = await queueHTML(page, 'body');7  console.log(html);8  await browser.close();9})();Using AI Code Generation
1const { queueHTML } = require("playwright-core/lib/server/frames");2const fs = require("fs");3const path = require("path");4const html = fs.readFileSync(path.join(__dirname, "index.html"), "utf8");5(async () => {6  await queueHTML(html);7})();Using AI Code Generation
1const { queueHTML } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const html = '<button>Click me</button>';3queueHTML(html);4const { queueHTML } = require('playwright/lib/server/supplements/recorder/recorderSupplement');5const html = '<button>Click me</button>';6queueHTML(html);Using AI Code Generation
1const { queueHTML } = require('@playwright/test');2const path = require('path');3(async () => {4  await queueHTML({5    path: path.join(__dirname, 'report.html'),6  });7})();Using AI Code Generation
1const { chromium } = require("playwright");2const path = require("path");3const fs = require("fs");4const pptr = require("playwright");5const { Page } = require("playwright/lib/client/page");6(async () => {7  const browser = await chromium.launch({ headless: false });8  const page = await browser.newPage();9  await page.screenshot({ path: "google.png" });10  await page.evaluate(() => {11    document.body.innerHTML = "";12  });13  await page.queueHTML("<h1>hello</h1>");14  await page.screenshot({ path: "google.png" });15  await browser.close();16})();17const { Page } = require("./page");18const { helper } = require("../helper");19const { assert } = require("../assert");20class InternalPage extends Page {21  constructor(delegate, browserContext, pageOrError) {22    super(delegate, browserContext, pageOrError);23  }24  async queueHTML(html) {25    const contextId = await this._mainFrame._utilityContext();26    const { result } = await this._delegate.evaluateInternal({27    });28    await this._mainFrame._utilityContextCreatedForTests();29    await this._delegate.setDocumentContent({ frameId: this._mainFrame._id, html: result.value });30  }31}32module.exports = { InternalPage };33const { Page } = require("../page");34const { helper } = require("../helper");35const { assert } = require("../assert");36class CRPage extends Page {37  constructor(session, browserContext, pageOrError) {38    super(session, browserContext, pageOrError);39  }40  async queueHTML(html) {41    const contextId = await this._mainFrame._utilityContext();42    const { result } = await this._delegate.evaluateInternal({Using AI Code Generation
1const { chromium } = require('playwright');2const fs = require('fs');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: 'test.png' });8  const html = await page.queueHTML();9  fs.writeFileSync('test.html', html);10  await browser.close();11})();12{13    {14      "webRoot": "${workspaceFolder}"15    }16}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!!
