Best JavaScript code snippet using playwright-internal
library.js
Source:library.js
...284 }285 }286}287// EVENT HANDLER HELPERS288function getEventTarget(e) {289 e = e || window.event;290 return e.target || e.srcElement;291 }292function triggerForm() { 293 if (addNewBookButton.value == '+' && addNewBookForm.style.display == 'grid') { 294 addNewBookButton.value = '-'; 295 shelf.style.display = 'none';296 if (newBookTitle.value.length > 0) {297 document.querySelector('#title input').value = newBookTitle.value;298 document.querySelector('#author input').focus();299 } else {300 document.querySelector('#title input').focus();301 }302 } else { 303 addNewBookButton.value = '+'; 304 shelf.style.display = 'grid';305 }306}307function hideNewBookForm() {308 addNewBookForm.reset();309 document.querySelector('#description textarea').textContent = '';310 for (let div of document.querySelectorAll('.warning')) { div.style.display = 'none'; }311 document.getElementById('cover').removeChild(document.getElementById('cover').lastElementChild);312 document.getElementById('cover').appendChild(document.createElement('div'));313 addNewBookForm.style.display = 'none';314 triggerForm();315 newBookTitle.value = '';316 newBookTitle.focus();317}318function searchGBooks(title, author) {319 if (document.getElementById('no-gbooks-warning').style.display == 'block') document.getElementById('no-gbooks-warning').style.display = 'none';320 fetch(`https://www.googleapis.com/books/v1/volumes?q=intitle:${title}+inauthor:${author}`)321 .then(function(result) { return result.json(); })322 .then(function(fetch) { 323 if (fetch.items !== undefined) {324 document.querySelector('#description textarea').textContent = fetch.items[0].volumeInfo.description;325 document.querySelector('#cover-url input').value = fetch.items[0].volumeInfo.imageLinks.thumbnail;326 document.querySelector('#pages input').value = fetch.items[0].volumeInfo.pageCount;327 document.querySelector('#pages input').focus(); setTimeout(() => document.querySelector('#cover-url input').focus(), 1);328 } else { 329 document.getElementById('no-gbooks-warning').style.display = 'block';330 return 0 331 }332 }),333 function(error) { return 0 };334}335// EVENT HANDLERS336function handleNewURL(e) {337 let book = getEventTarget(e).parentNode.parentNode;338 let cover = book.childNodes[1];339 let newCover = generateCoverImg(getEventTarget(e).value);340 if (newCover.getAttribute('alt') == 'Cover image did not load correctly.') {341 newCover = generateDummyCover(myLibrary[getEventTarget(e).dataset.id].author, myLibrary[getEventTarget(e).dataset.id].title) 342 }343 book.removeChild(cover);344 book.insertBefore(newCover, book.childNodes[1]);345}346function saveURL(e) {347 myLibrary[getEventTarget(e).dataset.id].cover = getEventTarget(e).firstChild.value;348 updateLocalStorage(); render();349}350function handlePagesRead(e) {351 if (getEventTarget(e).value == '\u203a') { 352 getEventTarget(e).setAttribute('value', '\u2713');353 getEventTarget(e).setAttribute('alt', 'save');354 getEventTarget(e).parentNode.removeChild(getEventTarget(e).parentNode.childNodes[0]);355 getEventTarget(e).parentNode.removeChild(getEventTarget(e).parentNode.childNodes[0]);356 getEventTarget(e).parentNode.insertBefore(buildChangePagesReadForm(getEventTarget(e).dataset.id), getEventTarget(e));357 getEventTarget(e).parentNode.firstChild.addEventListener('submit', handlePagesRead);358 const changeField = document.getElementById('change-pages-read');359 changeField.focus();360 changeField.addEventListener('keyup', function() {361 if (!/[0-9]/.test(this.value.substr(-1))) this.value = this.value.slice(0, this.value.length-1);362 if (parseInt(this.value) > this.max) this.value = this.max;363 });364 } else if (getEventTarget(e). value == '\u2713') {365 let input = getEventTarget(e).parentNode.firstChild.lastChild.value, id = getEventTarget(e).dataset.id;366 myLibrary[id].pagesRead = input === '' ? myLibrary[id].pagesRead : input;367 getEventTarget(e).parentNode.removeChild(getEventTarget(e).parentNode.childNodes[0]);368 const progressBar = generateProgressBar(id, withButton = false);369 getEventTarget(e).parentNode.insertBefore(progressBar[0], getEventTarget(e));370 getEventTarget(e).parentNode.insertBefore(progressBar[1], getEventTarget(e));371 getEventTarget(e).setAttribute('value', '\u203a');372 getEventTarget(e).setAttribute('alt', 'change pages read');373 filterBooks();374 }375}376function handleReadToggle(e) {377 myLibrary[getEventTarget(e).dataset.id].read = !myLibrary[getEventTarget(e).dataset.id].read;378 if (myLibrary[getEventTarget(e).dataset.id].read) {379 getEventTarget(e).value = '\u00d7'; // mult. sign380 getEventTarget(e).parentNode.firstChild.style.backgroundColor = 'rgba(4, 74, 77, 0.9)'; // green381 getEventTarget(e).parentNode.firstChild.textContent = 'read';382 } else {383 getEventTarget(e).value = '\u2713'; // checkmark384 getEventTarget(e).parentNode.firstChild.style.backgroundColor = 'rgba(169,3,41,0.9)'; // red385 getEventTarget(e).parentNode.firstChild.textContent = 'unread'; 386 }387}388function handleInfo(e) {389 getEventTarget(e).parentNode.parentNode.lastChild.style.visibility = 'visible'; 390}391function handleChangeCover(e) {392 getEventTarget(e).style.visibility = 'hidden';393 getEventTarget(e).parentNode.appendChild(buildURLChangeForm(getEventTarget(e).dataset.id));394 getEventTarget(e).parentNode.lastChild.firstChild.focus();395 getEventTarget(e).parentNode.lastChild.firstChild.addEventListener('keyup', handleNewURL);396 getEventTarget(e).parentNode.lastChild.addEventListener('submit', saveURL);397}398function handleBack(e) {399 getEventTarget(e).parentNode.parentNode.style.visibility = 'hidden';400 getEventTarget(e).parentNode.parentNode.parentNode.childNodes[1].style.visibility = 'visible';401 getEventTarget(e).parentNode.parentNode.parentNode.childNodes[2].style.visibility = 'visible';402}403function handleDelete(e) {404 myLibrary.splice(getEventTarget(e).dataset.id, 1);405 updateLocalStorage(); render();406}407function handleEdit(e) {408 if (getEventTarget(e).value == 'edit') {409 getEventTarget(e).value = 'save';410 getEventTarget(e).parentNode.parentNode.childNodes[1].style.display = 'none';411 getEventTarget(e).parentNode.parentNode.appendChild(buildEditForm(getEventTarget(e).dataset.id));412 } else {413 getEventTarget(e).value = 'edit';414 getEventTarget(e).parentNode.parentNode.childNodes[1].textContent = getEventTarget(e).parentNode.parentNode.childNodes[2].firstChild.value;415 getEventTarget(e).parentNode.parentNode.childNodes[1].style.display = 'block';416 myLibrary[getEventTarget(e).dataset.id].description = getEventTarget(e).parentNode.parentNode.childNodes[2].firstChild.value;417 getEventTarget(e).parentNode.parentNode.removeChild(getEventTarget(e).parentNode.parentNode.childNodes[2]); 418 }419}420function handleBookButtons(e) {421 if (getEventTarget(e).classList.contains('info')) return handleInfo(e);422 if (getEventTarget(e).classList.contains('delete')) return handleDelete(e);423 if (getEventTarget(e).classList.contains('change-pages')) return handlePagesRead(e);424 if (getEventTarget(e).classList.contains('back')) return handleBack(e);425 if (getEventTarget(e).classList.contains('edit')) return handleEdit(e);426 if (getEventTarget(e).classList.contains('change-cover')) return handleChangeCover(e);427 if (getEventTarget(e).classList.contains('read-toggle')) return handleReadToggle(e);428}429 430// EVENT LISTENERS431clearStorageButton.addEventListener('mousedown', clearStorage);432clearStorageButton.addEventListener('mouseup', render);433shelf.addEventListener('click', e => handleBookButtons(e));434addNewBookButton.addEventListener('click', () => {435 addNewBookForm.style.display == 'grid' ? addNewBookForm.style.display = 'none' 436 : addNewBookForm.style.display = 'grid';437 triggerForm();438});439newBookTitle.addEventListener('keydown', (e) => {440 if (!e.repeat && e.key == 'Enter') {441 addNewBookForm.style.display = 'grid';...
ApiContainer.js
Source:ApiContainer.js
...34 this.hireGuiEventHandlers();35 this._auth()36 }37 async _auth() {38 this.getEventTarget().dispatchEvent(new Event("beforeInitAuthProviders"));39 await this._initAuthProviders();40 this.getEventTarget().dispatchEvent(new Event("afterInitAuthProviders"));41 this._renderApiAuthorization();42 this._applyAuth();43 }44 _applyAuth() {45 let container = this;46 let hasAuthorized = false;47 let apply = (function (auth) {48 if (!this.api.isReady() && auth.isAuthorized()) {49 hasAuthorized = true;50 ApiContainer._debug('INIT INITIATED')51 this.api.init(ApiContainer.getBackendUrl(), auth.getBearerToken(), this.userAgent)52 .then(function () {53 container.getEventTarget().dispatchEvent(new Event("apiAuthorized"));54 })55 } else if (auth.isAuthorized()) {56 hasAuthorized = true;57 }58 }).bind(this);59 this.getList().forEach(apply);60 if (!hasAuthorized) {61 ApiContainer._debug('[ApiContainer] hasAuthorized === false')62 container.authToken = null;63 container.api.disable();64 container.taskItems = [];65 container.getEventTarget().dispatchEvent(new Event("apiAuthorized"));66 }67 }68 _removeAuth() {69 this.authToken = null;70 }71 getList() {72 return this.authProviderList;73 }74 getEventTarget() {75 return this.eventTarget;76 }77 _initAuthProviders() {78 let container = this;79 return new Promise(function (resolve, reject) {80 let authProviderListToHandle = container.getList().length;81 container.getList().forEach(function (api) {82 ApiContainer._debug('api before init');83 api.init()84 .finally(function () {85 ApiContainer._debug('api finally');86 authProviderListToHandle--;87 if (authProviderListToHandle < 1) {88 ApiContainer._debug("authProviderListToHandle left: " + authProviderListToHandle);89 ApiContainer._debug('after finally');90 resolve();91 } else {92 ApiContainer._debug("authProviderListToHandle left: " + authProviderListToHandle);93 }94 });95 });96 });97 }98 _renderApiAuthorization() {99 let container = this;100 this.getEventTarget().dispatchEvent(new Event("startLoadingAuthForms"));101 const authItems = [];102 let authQty = 0;103 let hasAuth = false;104 this.getList().forEach(function (api) {105 if (authQty > 0) {106 // only one auth required107 return;108 }109 ApiContainer._debug('rendering auth form');110 if (!api.isAuthorized()) {111 ApiContainer._debug('is not authorized; Rendering auth form');112 authItems.push(api.getAuthForm());113 } else {114 authQty++;115 ApiContainer._debug('is authorized; Rendering logout form');116 authItems.push(api.getLogoutForm());117 }118 });119 if (!authQty) {120 this.getEventTarget().dispatchEvent(new Event("changeActiveTabToLoginList"));121 } else {122 this.getEventTarget().dispatchEvent(new Event("changeActiveTabToTasks"));123 }124 ApiContainer._debug('Actual rendering of forms');125 render(126 authItemsTemplate(authItems),127 document.getElementById('authContainer')128 );129 ApiContainer._debug('initializing events of forms');130 this.getList().forEach(function (api) {131 ApiContainer._debug('initializing form events');132 if (!container.authToken && !api.isAuthorized()) {133 api.initAuthFormEvents();134 } else {135 api.initLogoutFormEvents();136 }137 });138 this.getEventTarget().dispatchEvent(new Event("finishLoadingAuthForms"));139 }140 /*141 * Callback to render all the task async142 */143 renderGroups(tasks) {144 this.taskItems = this.taskItems.concat(tasks);145 this.taskItems = this.taskItems.sort(function(a, b){146 return new Date(b.date) - new Date(a.date);147 });148 ApiContainer._debug(tasks);149 render(150 taskItemsTemplate(this.taskItems),151 document.getElementById('taskList')152 );153 }154 initMainListTab() {155 ApiContainer._debug('initMainListTab()')156 let container = this;157 container.taskItems = [];158 if (!this.api.isReady()) {159 ApiContainer._debug('API IS NOT READY');160 return;161 }162 let beforeRendering = (function () {163 this.getEventTarget().dispatchEvent(new Event("startLoadingTasks"));164 }).bind(container);165 let afterRendering = (function () {166 this.getEventTarget().dispatchEvent(new Event("finishLoadingTasks"));167 }).bind(container);168 beforeRendering();169 ApiContainer._debug('[ApiContainer] GROUP ')170 this.api.getGroupProfiles(this.api.group.id).then(this.renderGroups.bind(container))171 .catch(function (e) {172 console.error(e);173 container.renderGroups([]);174 })175 .finally(afterRendering);176 }177 hireGuiEventHandlers() {178 let container = this;179 let tasksProgressBars = document.querySelectorAll("#tasks > .progress");180 let loginListProgressBars = document.querySelectorAll("#loginList > .progress");181 var commonProgressBars = document.querySelectorAll("#body > .container > .progress");182 this.getEventTarget().addEventListener("apiAuthorized", function() {183 ApiContainer._info("[Event] apiAuthorized");184 container.getEventTarget().dispatchEvent(new Event("refreshFeedEvent"));185 });186 this.getEventTarget().addEventListener("refreshAuthEvent", function() {187 ApiContainer._info("[Event] refreshAuthEvent");188 container._renderApiAuthorization();189 container._applyAuth();190 //After refresing some authorizations we should refresh feed also191 container.getEventTarget().dispatchEvent(new Event("refreshFeedEvent"));192 });193 this.getEventTarget().addEventListener("refreshFeedEvent", async function() {194 ApiContainer._info("[Event] refreshFeedEvent");195 container.taskItems = [];196 container.initMainListTab();197 });198 this.getEventTarget().addEventListener("beforeInitAuthProviders", function() {199 ApiContainer._info("[Event] beforeInitAuthProviders");200 commonProgressBars.forEach(ApiContainer.enableProgress);201 });202 this.getEventTarget().addEventListener("afterInitAuthProviders", function() {203 ApiContainer._info("[Event] afterInitAuthProviders");204 commonProgressBars.forEach(ApiContainer.disableProgress);205 });206 this.getEventTarget().addEventListener("startLoadingTasks", function() {207 ApiContainer._info("[Event] startLoadingTasks");208 tasksProgressBars.forEach(ApiContainer.enableProgress);209 });210 this.getEventTarget().addEventListener("finishLoadingTasks", function() {211 ApiContainer._info("[Event] finishLoadingTasks");212 tasksProgressBars.forEach(ApiContainer.disableProgress);213 });214 this.getEventTarget().addEventListener("startLoadingAuthForms", function() {215 ApiContainer._info("[Event] startLoadingAuthForms");216 loginListProgressBars.forEach(ApiContainer.enableProgress);217 });218 this.getEventTarget().addEventListener("finishLoadingAuthForms", function() {219 ApiContainer._info("[Event] finishLoadingAuthForms");220 loginListProgressBars.forEach(ApiContainer.disableProgress);221 });222 this.getEventTarget().addEventListener("changeActiveTabToLoginList", function(e) {223 ApiContainer._info("[Event] changeActiveTabToLoginList");224 container._removeAuth();225 container.initMainListTab();226 document.querySelectorAll("#main-tabs > li > a").forEach(function(item) {227 if (item.attributes.href.value === "#loginList") {228 item.dispatchEvent(new MouseEvent('click', {bubbles: true}));229 }230 });231 });232 this.getEventTarget().addEventListener("changeActiveTabToTasks", function(e) {233 ApiContainer._info("[Event] changeActiveTabToTasks");234 document.querySelectorAll("#main-tabs > li > a").forEach(function(item) {235 if (item.attributes.href.value === "#tasks") {236 item.dispatchEvent(new MouseEvent('click', {bubbles: true}));237 }238 });239 });240 document.getElementById("group-btn-add").addEventListener("click", function (e) {241 e.preventDefault();242 ApiContainer._debug(e);243 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {244 var currTab = tabs[0];245 if (currTab) {246 container.api.addWebsite(currTab.url).then(function (website) {...
editorbase.js
Source:editorbase.js
...176 * @protected177 */178pear.ui.editor.EditorBase.prototype.getKeyHandler = function() {179 return this.keyHandler_ ||180 (this.keyHandler_ = new goog.events.KeyHandler(this.getEventTarget()));181};182/**183 * Root DOM of Editor184 */185pear.ui.editor.EditorBase.prototype.createEditorRootDom = function() {186 this.rootElement_ = goog.dom.createDom(187 'div', 'pear-grid-cell-data-content pear-grid-cell-editor');188 goog.dom.appendChild(this.getMediator().getGridCell().getElement(),189 this.rootElement_);190 goog.events.listen(this.getKeyHandler(),191 goog.events.KeyHandler.EventType.KEY,192 this.handleKeyEvent, false, this);193 goog.events.listen(this.getEventTarget(),194 goog.events.EventType.CLICK, this.handleMouseEvent);195 goog.events.listen(this.getEventTarget(),196 goog.events.EventType.MOUSEDOWN, this.handleMouseEvent);197 goog.events.listen(this.getEventTarget(),198 goog.events.EventType.MOUSEUP, this.handleMouseEvent);199};200/**201 * handle Key event on Editor202 * @param {goog.events.KeyEvent} e Key event to handle.203 * @protected204 * @return {boolean}205 */206pear.ui.editor.EditorBase.prototype.handleKeyEvent = function(e) {207 // Do not handle the key event if any modifier key is pressed.208 if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) {209 return false;210 }211 // Either nothing is highlighted, or the highlighted control didn't handle212 // the key event, so attempt to handle it here.213 switch (e.keyCode) {214 case goog.events.KeyCodes.ESC:215 case goog.events.KeyCodes.TAB:216 this.rollback();217 break;218 case goog.events.KeyCodes.ENTER:219 this.setValueFromEditor();220 this.commit();221 break;222 default:223 return false;224 }225 return true;226};227/**228 * create Editor DOM229 * @protected230 */231pear.ui.editor.EditorBase.prototype.createEditorDom = function() {};232/**233 * handleMouseEvent234 * @param {goog.events.BrowserEvent} be Key event to handle.235 * @protected236 */237pear.ui.editor.EditorBase.prototype.handleMouseEvent = function(be) {238 be.preventDefault();239};240/**241 * [detachEvents_ description]242 * @private243 */244pear.ui.editor.EditorBase.prototype.detachEvents_ = function() {245 goog.events.unlisten(this.getEventTarget(),246 goog.events.EventType.CLICK, this.handleMouseEvent);247 goog.events.unlisten(this.getEventTarget(),248 goog.events.EventType.MOUSEDOWN, this.handleMouseEvent);249 goog.events.unlisten(this.getEventTarget(),250 goog.events.EventType.MOUSEUP, this.handleMouseEvent);251 goog.dom.removeNode(this.getEventTarget());252 this.rootElement_ = null;253};254/**255 * @inheritDoc256 * @protected257 */258pear.ui.editor.EditorBase.prototype.disposeInternal = function() {259 this.oldValue_ = null;260 this.newValue_ = null;261 this.mediator_ = null;262 this.open_ = null;263 this.detachEvents_();264 pear.ui.editor.EditorBase.superClass_.disposeInternal.call(this);265};
event_installer.js
Source:event_installer.js
...54ydn.db.tr.Storage.prototype.addEventListener = function(type, handler,55 opt_capture, opt_handlerScope) {56 if (type == 'ready') {57 // remove callback reference since 'ready' event is invoked only once.58 goog.events.listenOnce(this.getEventTarget(), type, handler, opt_capture,59 opt_handlerScope);60 } else {61 if (goog.DEBUG) {// don't allow to added non existing event type62 var event_types = this.getEventTypes();63 var checkType = function(type) {64 if (!goog.array.contains(event_types,65 type)) {66 throw new ydn.debug.error.ArgumentException('Invalid event type "' +67 type + '"');68 }69 };70 if (goog.isArrayLike(type)) {71 for (var i = 0; i < type.length; i++) {72 checkType(type[i]);73 }74 } else {75 checkType(type);76 }77 }78 goog.events.listen(this.getEventTarget(), type, handler, opt_capture,79 opt_handlerScope);80 }81};82/**83 * Removes an event listener from the event target. The handler must be the84 * same object as the one added. If the handler has not been added then85 * nothing is done.86 *87 * @param {string} type The type of the event to listen for.88 * @param {Function} handler The function to handle the event. The89 * handler can also be an object that implements the handleEvent method90 * which takes the event object as argument.91 * @param {boolean=} opt_capture In DOM-compliant browsers, this determines92 * whether the listener is fired during the capture or bubble phase93 * of the event.94 * @param {Object=} opt_handlerScope Object in whose scope to call95 * the listener.96 */97ydn.db.tr.Storage.prototype.removeEventListener = function(98 type, handler, opt_capture, opt_handlerScope) {99 goog.events.unlisten(this.getEventTarget(), type, handler, opt_capture, opt_handlerScope);100};101/**102 * @inheritDoc103 */104ydn.db.tr.Storage.prototype.dispatchDbEvent = function(event) {105 this.getEventTarget().dispatchEvent(event);...
study.js
Source:study.js
...8var target;9var w;10function select()11{12 function getEventTarget(e) {13 e = e || window.event;14 return e.target || e.srcElement; 15 }16 17 var ul = document.getElementById('test');18 ul.onclick = function(event) {19 target = getEventTarget(event);20 // alert(target.innerText); 21 window.location.href = "study_course.html";22 w = target.innerText;23 localStorage.setItem("branch",w);24 //document.getElementById("branch").innerHTML = w;25 };26 var ul = document.getElementById('test1');27 ul.onclick = function(event) {28 target = getEventTarget(event);29 //alert(target.innerText);30 window.location.href = "study_course.html";31 w=target.innerText;32 localStorage.setItem("branch",w);33 };34 var ul = document.getElementById('test2');35 ul.onclick = function(event) {36 target = getEventTarget(event);37 window.location.href = "study_course.html";38 //alert(target.innerText);39 w=target.innerText;40 localStorage.setItem("branch",w);41 };42 var ul = document.getElementById('test3');43 ul.onclick = function(event) {44 target = getEventTarget(event);45 //alert(target.innerText);46 window.location.href = "study_course.html";47 w=target.innerText;48 localStorage.setItem("branch",w);49 };50 var ul = document.getElementById('test4');51 ul.onclick = function(event) {52 target = getEventTarget(event);53 //alert(target.innerText);54 window.location.href = "study_course.html";55 w=target.innerText;56 localStorage.setItem("branch",w);57 };58 var ul = document.getElementById('test5');59 ul.onclick = function(event) {60 target = getEventTarget(event);61 window.location.href = "study_course.html";62 //alert(target.innerText);63 w=target.innerText;64 localStorage.setItem("branch",w);65 };66
...
boxxer.test.js
Source:boxxer.test.js
...29 });30});31test('functionality', function() {32 var mockEvent = { target: 'foo' };33 deepEqual(boxxer.utils.getEventTarget(mockEvent), mockEvent.target, '.utils.getEventTarget() - target');34 mockEvent = { srcElement: 'foo' };35 deepEqual(boxxer.utils.getEventTarget(mockEvent), mockEvent.srcElement, '.utils.getEventTarget() - srcElement');36 deepEqual(boxxer.utils.getBody(), document.body, '.utils.getBody()');37 var div = document.createElement('div');38 boxxer.init(div);39 deepEqual(boxxer.utils.getRenderer(), div.childNodes[0], '.utils.getRenderer()');...
slides.js
Source:slides.js
1var slides = {};2(function() {3 // IE does not know about the target attribute. It looks for srcElement4 // This function will get the event target in a browser-compatible way5 function getEventTarget(e) {6 e = e || window.event;7 return e.target || e.srcElement; 8 }9 function getImage(event) {10 return getEventTarget(event).parentNode.parentNode.firstChild.firstChild11 }12 function sequenceNumber(file) {13 var match = /.*-([0-9]+)\.[a-z]+$/.exec(file)14 return parseInt(match[1])15 }16 function subsequentImage(file, num) {17 var start = /[0-9]+\.[a-z]+$/.exec(file).index18 var end = /\.[a-z]+$/.exec(file).index19 return file.substring(0, start) + num + file.substring(end)20 }21 this.prev = function(event) {22 var img = getImage(event);23 var num = sequenceNumber(img.src)24 if (num > 0) img.src = subsequentImage(img.src, num - 1)25 if (num == 1) getEventTarget(event).disabled = true26 getEventTarget(event).parentNode.children[1].disabled = false27 }28 this.next = function(event, nimages) {29 var img = getImage(event);30 var num = sequenceNumber(img.src)31 if (num < parseInt(nimages)) img.src = subsequentImage(img.src, num + 1)32 if (num == parseInt(nimages) - 1) getEventTarget(event).disabled = true33 getEventTarget(event).parentNode.children[0].disabled = false34 }35 36 this.startover = function(event) {37 var img = getImage(event);38 img.src = subsequentImage(img.src, 0)39 getEventTarget(event).parentNode.children[0].disabled = true40 getEventTarget(event).parentNode.children[1].disabled = false41 }...
getEventTarget.js
Source:getEventTarget.js
...15 *16 * @param {object} nativeEvent Native browser event.17 * @return {DOMEventTarget} Target node.18 */19function getEventTarget(nativeEvent) {20 var target = nativeEvent.target || nativeEvent.srcElement || window;21 // Normalize SVG <use> element events #496322 if (target.correspondingUseElement) {23 target = target.correspondingUseElement;24 }25 // Safari may fire events on text nodes (Node.TEXT_NODE is 3).26 // @see http://www.quirksmode.org/js/events_properties.html27 return target.nodeType === 3 ? target.parentNode : target;28}29module.exports = getEventTarget;30//////////////////31// WEBPACK FOOTER32// ./~/react/lib/getEventTarget.js33// module id = 459...
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/client/selectorEngine');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 target = await getEventTarget(page, '.navbar__inner');8 console.log(target);9 await browser.close();10})();11ElementHandle {12 _channel: Connection {13 _events: [Object: null prototype] {},14 _callbacks: Map(0) {},15 _sessions: Map(0) {},16 _objects: Map(0) {},17 _transport: WebSocket {18 _events: [Object: null prototype] {},19 _extensions: {},
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/server/dom');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 page.on('response', async (response) => {8 const target = getEventTarget(response.request());9 await target.evaluate((target) => {10 console.log('Target: ', target);11 });12 });13 await browser.close();14})();15Target: {
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/internal/frames');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 page.on('click', async (event) => {8 const target = getEventTarget(event);9 console.log(target);10 });11 await page.click('input[name="btnK"]');12 await browser.close();13})();14ElementHandle {15 _context: BrowserContext {16 _browser: Browser {17 },18 _options: { viewport: null, userAgent: null, deviceScaleFactor: null },19 _permissions: {},20 _origins: {},21 _channel: BrowserContextChannel {22 },23 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000, _timeout: 0 },24 _pageBindings: Map(0) {},25 _workers: Map(0) {},26 _downloads: Map(0) {},27 _ownedPages: Set(1) { [Circular] },28 _ownedWorkers: Set(0) {}29 },30 _page: Page {31 _channel: PageChannel {32 },33 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000, _timeout: 0 },34 _workers: Map(0) {},35 _downloads: Map(0) {},36 _pageBindings: Map(0) {},37 _frameManager: FrameManager {
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/client/events');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.click('input[name="q"]');7 await page.keyboard.type('Hello World');8 const target = await getEventTarget(page, 'input[name="q"]');9 console.log(target);10 await browser.close();11})();12ElementHandle {13 _context: BrowserContext {14 _browser: Browser {15 },16 _options: {
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/internal/frames');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 searchBox = await page.$('input[title="Search"]');8 const target = await getEventTarget(page, searchBox);9 console.log(target);10 await browser.close();11})();12{13 _attributes: {
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/internal/frames');2const { chromium } = require('playwright');3const fs = require('fs');4(async () => {5 const browser = await chromium.launch();6 const page = await browser.newPage();7 const eventTarget = await getEventTarget(page.mainFrame());8 const event = new Event('click');9 eventTarget.dispatchEvent(event);10 await page.screenshot({ path: 'screenshot.png' });11 await browser.close();12})();13 at Chromium._onMessage (/Users/****/playwright/node_modules/playwright/lib/chromium/crConnection.js:191:23)14 at Connection._onMessage (/Users/****/playwright/node_modules/playwright/lib/chromium/crConnection.js:110:17)15 at WebSocketTransport._ws.addEventListener.event (/Users/****/playwright/node_modules/playwright/lib/chromium/crConnection.js:87:45)16 at WebSocketTransport._ws.addEventListener.event (/Users/****/playwright/node_modules/playwright/lib/chromium/crConnection.js:87:45)17 at WebSocket.onMessage (/Users/****/playwright/node_modules/ws/lib/event-target.js:120:16)18 at WebSocket.emit (events.js:315:20)19 at Receiver.receiverOnMessage (/Users/****/playwright/node_modules/ws/lib/websocket.js:789:20)20 at Receiver.emit (events.js:315:20)21 at Receiver.dataMessage (/Users/****/playwright/node_modules/ws/lib/receiver.js:437:14)22 at Receiver.getData (/Users/****/playwright/node_modules/ws/lib/receiver.js:367:17)
Using AI Code Generation
1const { chromium } = require("playwright");2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click("text=Sign in");7 const target = await page._delegate.getEventTarget("click");8 console.log(target);9 await browser.close();10})();11ElementHandle {12 _context: BrowserContext {13 _browser: Browser {14 },15 },16 _channel: Connection {17 _events: [Object: null prototype] {},
Using AI Code Generation
1const { getEventTarget } = require('playwright/lib/server/dom.js');2const element = await page.$('#element');3const target = getEventTarget(element);4const { x, y } = await target.boundingBox();5console.log(x, y);6const { getEventTarget } = require('playwright/lib/server/dom.js');7const element = await page.$('#element');8const target = getEventTarget(element);9const { x, y } = await target.boundingBox();10console.log(x, y);11const { getEventTarget } = require('playwright/lib/server/dom.js');12const element = await page.$('#element');13const target = getEventTarget(element);14const { x, y } = await target.boundingBox();15console.log(x, y);16const { getEventTarget } = require('playwright/lib/server/dom.js');17const element = await page.$('#element');18const target = getEventTarget(element);19const { x, y } = await target.boundingBox();20console.log(x, y);21const { getEventTarget } = require('playwright/lib/server/dom.js');22const element = await page.$('#element');23const target = getEventTarget(element);24const { x, y } = await target.boundingBox();25console.log(x, y);26const { getEventTarget } = require('playwright/lib/server/dom.js');27const element = await page.$('#element');28const target = getEventTarget(element);29const { x, y } = await target.boundingBox();30console.log(x, y);31const { getEventTarget } = require('playwright/lib/server/dom.js');32const element = await page.$('#element');33const target = getEventTarget(element);34const { x, y } = await target.boundingBox();35console.log(x, y);
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!!