How to use findFocusedNode method in Puppeteer

Best JavaScript code snippet using puppeteer

expander.js

Source:expander.js Github

copy

Full Screen

...266 } else if (CKE_EDITOR_REGEX.test(domain)) {267 replaceTextCKE(shortcut, autotext);268 } else {269 debugLog("Domain:", domain);270 replaceTextContentEditable(shortcut, autotext, findFocusedNode());271 }272 }273 // Always clear the buffer after a shortcut fires274 clearTypingBuffer();275 }); // END - getClipboardData()276 } // END - if (autotext)277 else { // Error278 console.log('Invalid input, missing autotext or textinput parameters.');279 }280 }281 // Specific handler for regular textarea and input elements282 function replaceTextRegular(shortcut, autotext, textInput)283 {284 var cursorPosition = getCursorPosition(textInput);285 // Fix for input[type=email] and input[type=number]286 if (cursorPosition === 0 && textInput.nodeName == "INPUT")287 {288 var type = textInput.getAttribute('type').toUpperCase();289 if (type == 'EMAIL' || type == 'NUMBER') {290 cursorPosition = textInput.value.length;291 }292 }293 textInput.value = replaceText(294 textInput.value,295 shortcut,296 autotext,297 cursorPosition298 );299 setCursorPosition(textInput, cursorPosition - shortcut.length + autotext.length);300 }301 // Specific handler for Facebook element replacements302 function replaceTextFacebook(shortcut, autotext, textInput)303 {304 debugLog("Domain: Facebook");305 var text;306 var cursorPosition = getCursorPosition(textInput);307 // Check if it is the search bar vs comments308 if (hasParentSelector(textInput, 'div', ['textInput']))309 {310 debugLog('facebook search bar');311 var span = textInput.querySelector('span'); // Can only get collection312 if (span) {313 textInput = span;314 }315 // Get text and replace it316 text = textInput.textContent;317 textInput.textContent = replaceText(318 text,319 shortcut,320 autotext,321 cursorPosition322 );323 // Set new cursor position324 setCursorPosition(textInput, cursorPosition - shortcut.length + autotext.length);325 }326 else if (hasParentSelector(textInput,'div', ['UFICommentContainer'])) {327 debugLog('facebook comments'); // doesn't work, due to ReactJS framework328 }329 else330 {331 // Get text and replace it332 text = textInput.textContent;333 textInput.textContent = replaceText(334 text,335 shortcut,336 autotext,337 cursorPosition338 );339 // Set new cursor position340 setCursorPosition(textInput,341 cursorPosition - shortcut.length + autotext.length);342 }343 }344 // Specific handler for Basecamp iframe replacements345 function replaceTextBasecamp(shortcut, autotext)346 {347 debugLog("Domain: Basecamp");348 // Get the focused / selected text node349 var iframeWindow = document.querySelector(SELECTOR_BASECAMP_EDIT).contentWindow;350 var node = findFocusedNode(iframeWindow);351 debugLog("node:", node);352 // Pass onto editable iframe text handler353 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);354 }355 // Specific handler for Outlook iframe replacements356 function replaceTextOutlook(shortcut, autotext)357 {358 debugLog("Domain: Outlook");359 // Get the focused / selected text node360 var iframeWindow = document.getElementById(SELECTOR_OUTLOOK_EDIT.substr(1))361 .contentWindow; // Need to cut off the # sign362 var node = findFocusedNode(iframeWindow);363 debugLog("node:", node);364 // Pass onto editable iframe text handler365 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);366 }367 // Specific handler for Evernote iframe replacements368 function replaceTextEvernote(shortcut, autotext)369 {370 debugLog("Domain: Evernote");371 // Get the focused / selected text node372 var iframeWindow = document.getElementById(SELECTOR_EVERNOTE_EDIT)373 .querySelector('iframe').contentWindow;374 var node = findFocusedNode(iframeWindow);375 debugLog("node:", node);376 // Pass onto editable iframe text handler377 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);378 }379 // Specific handler for Google Translate iframe text replacements380 function replaceTextGTT(shortcut, autotext)381 {382 debugLog("Domain: Google Translate");383 // Get the focused / selected text node384 var iframeWindow = document.querySelector(SELECTOR_GTT_EDIT)385 .querySelector('iframe').contentWindow;386 var node = findFocusedNode(iframeWindow);387 debugLog("node:", node);388 // Pass onto editable iframe text handler389 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);390 }391 // Specific handler for Google Docs iframe text replacements392 function replaceTextGDOCS(shortcut, autotext)393 {394 debugLog("Domain: Google Docs");395 // Get the focused / selected text node396 var iframeWindow = document.querySelector(SELECTOR_GDOCS_EDIT).contentWindow;397 var node = findFocusedNode(iframeWindow);398 debugLog("node:", node);399 // We can catch the text / event, but we can't seem to replace400 // or dispatch events to create the additional text401 // var e = $.Event('keydown');402 // e.which = 65; // Character 'A'403 // $(node).trigger(e);404 // $(node).trigger(e);405 // $(node).trigger(e);406 // $(node).trigger(e);407 //// Custom logic408 // var textInput = node;409 // debugLog(textInput);410 //411 // // Get and process text, update cursor position412 // var text = replaceHTML(node.textContent, shortcut, autotext, 0)413 // , multiline = false414 // , lines415 // ;416 //417 // // If autotext is multiline text, split by newlines, join with <br> tag instead418 // if (autotext.indexOf('\n') >= 0)419 // {420 // lines = text.split('\n');421 // text = lines.join('<br>');422 // multiline = true;423 // }424 //425 // // A way to insert HTML into a content editable div with raw JS.426 // // Creates an element with the HTML content, then transfers node by node427 // // to a new Document Fragment that replaces old node428 // // Source from: http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div429 // var el = document.createElement("div") // Used to store HTML430 // , frag = document.createDocumentFragment() // To replace old node431 // , cursorNode; // To track cursor position432 // el.innerHTML = text; // Set HTML to div, then move to frag433 // for (var tempNode; tempNode = el.firstChild; frag.appendChild(tempNode))434 // {435 // debugLog(tempNode.nodeType, tempNode);436 // if (tempNode.nodeType === Node.COMMENT_NODE437 // && tempNode.nodeValue == CURSOR_TRACKING_TAG) {438 // cursorNode = tempNode;439 // }440 // }441 // textInput.appendChild(frag); // add fragment of text442 //443 // // Set cursor position based off tracking node (or last child if we444 // // weren't able to find the cursor tracker), then remove tracking node445 // if (cursorNode) {446 // cursorNode.parentNode.removeChild(cursorNode);447 // }448 }449 // Specific handler for Atlassian frame editor text replacements450 function replaceTextAtlassian(shortcut, autotext)451 {452 debugLog("Domain: Atlassian");453 // Get the focused / selected text node454 var iframeWindow = document.querySelector(SELECTOR_ATLASSIAN_EDIT).contentWindow;455 var node = findFocusedNode(iframeWindow);456 debugLog("node:", node);457 // Pass onto editable iframe text handler458 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);459 }460 // Specific handler for Zendesk Inbox frame editor text replacements461 function replaceTextZendesk(shortcut, autotext)462 {463 debugLog("Domain: Zendesk");464 if (document.querySelector(SELECTOR_ZENDESK_INBOX_EDIT)) {465 // Get the focused / selected text node466 var iframeWindow = document.querySelector(SELECTOR_ZENDESK_INBOX_EDIT).contentWindow;467 var node = findFocusedNode(iframeWindow);468 debugLog("node:", node);469 // Pass onto editable iframe text handler470 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);471 } else {472 // To make it work with Zendesk's rich text editor473 replaceTextContentEditable(shortcut, autotext, findFocusedNode());474 }475 }476 // Specific handler for CKEditor iframe replacements477 function replaceTextCKE(shortcut, autotext)478 {479 debugLog("Editor: CKE");480 // Get the focused / selected text node481 var iframeWindow = document.querySelector(SELECTOR_CKE_EDIT)482 .contentWindow;483 var node = findFocusedNode(iframeWindow);484 debugLog("node:", node);485 // Pass onto editable iframe text handler486 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);487 }488 // Reusable handler for editable iframe text replacements489 function replaceTextContentEditable(shortcut, autotext, node, win)490 {491 // Find focused div instead of what's receiving events492 var textInput = node.parentNode;493 debugLog(textInput);494 // Get and process text, update cursor position495 var cursorPosition = getCursorPosition(textInput, win)496 , text = replaceHTML(node.textContent, shortcut, autotext, cursorPosition)497 , multiline = false498 , lines499 ;500 // If autotext is multiline text, split by newlines, join with <br> tag instead501 if (autotext.indexOf('\n') >= 0)502 {503 lines = text.split('\n');504 text = lines.join('<br>');505 multiline = true;506 }507 // A way to insert HTML into a content editable div with raw JS.508 // Creates an element with the HTML content, then transfers node by node509 // to a new Document Fragment that replaces old node510 // Source from: http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div511 var el = document.createElement("div") // Used to store HTML512 , frag = document.createDocumentFragment() // To replace old node513 , cursorNode; // To track cursor position514 el.innerHTML = text; // Set HTML to div, then move to frag515 for (var tempNode; tempNode = el.firstChild; frag.appendChild(tempNode))516 {517 debugLog(tempNode.nodeType, tempNode);518 if (tempNode.nodeType === Node.COMMENT_NODE519 && tempNode.nodeValue == CURSOR_TRACKING_TAG) {520 cursorNode = tempNode;521 }522 }523 textInput.replaceChild(frag, node); // Replace old node with frag524 // Set cursor position based off tracking node (or last child if we525 // weren't able to find the cursor tracker), then remove tracking node526 setCursorPositionAfterNode(cursorNode || textInput.lastChild, win);527 if (cursorNode) {528 cursorNode.parentNode.removeChild(cursorNode);529 }530 }531 // Replacing shortcut with autotext in text at cursorPosition532 function replaceText(text, shortcut, autotext, cursorPosition)533 {534 debugLog("cursorPosition:", cursorPosition);535 debugLog("currentText:", text);536 debugLog("shortcut:", shortcut);537 debugLog("expandedText:", autotext);538 // Replace shortcut based off cursorPosition539 return [text.slice(0, cursorPosition - shortcut.length),540 autotext, text.slice(cursorPosition)].join('');541 }542 // Replacing shortcut with autotext HTML content at cursorPosition543 function replaceHTML(text, shortcut, autotext, cursorPosition)544 {545 debugLog("cursorPosition:", cursorPosition);546 debugLog("currentText:", text);547 debugLog("shortcut:", shortcut);548 debugLog("expandedText:", autotext);549 // If autotext expansion already has cursor tag in it, don't insert550 var cursorTag = (autotext.indexOf(CURSOR_TRACKING_HTML) >= 0)551 ? "" : CURSOR_TRACKING_HTML;552 // Replace shortcut based off cursorPosition,553 // insert tracking tag for cursor if it isn't already defined in autotext554 return [text.slice(0, cursorPosition - shortcut.length),555 autotext, cursorTag, text.slice(cursorPosition)].join('');556 }557 // Find node that has text contents that matches text558 function findMatchingTextNode(div, text)559 {560 return $(div).contents().filter(function() {561 return (this.nodeType == Node.TEXT_NODE) // Return all text nodes562 && (this.nodeValue.length == text.length); // with same text length563 }).filter(function() {564 return (this.nodeValue == text); // Filter for same text565 }).first().get(0);566 }567 // Find node that user is editing right now, for editable divs568 // Optional passed window to perform selection find on569 function findFocusedNode(win)570 {571 // Use default window if not given window to search in572 if (!win) {573 win = window;574 }575 // Look for selection576 if (win.getSelection) {577 var selection = win.getSelection();578 if (selection.rangeCount) {579 return selection.getRangeAt(0).startContainer;580 }581 }582 return null;583 }...

Full Screen

Full Screen

ate.js

Source:ate.js Github

copy

Full Screen

...271 } else if (CKE_EDITOR_REGEX.test(domain)) {272 replaceTextCKE(shortcut, autotext);273 } else {274 console.log('Domain:', domain);275 replaceTextContentEditable(shortcut, autotext, findFocusedNode());276 }277 }278 // Always clear the buffer after a shortcut fires279 clearTypingBuffer();280 }); // END - getClipboardData()281 } // END - if (autotext)282 else { // Error283 console.log('Invalid input, missing autotext or textinput parameters.');284 }285 }286 // Specific handler for regular textarea and input elements287 function replaceTextRegular(shortcut, autotext, textInput)288 {289 var cursorPosition = getCursorPosition(textInput);290 // Fix for input[type=email] and input[type=number]291 if (cursorPosition === 0 && textInput.nodeName == 'INPUT')292 {293 var type = textInput.getAttribute('type').toUpperCase();294 if (type == 'EMAIL' || type == 'NUMBER') {295 cursorPosition = textInput.value.length;296 }297 }298 textInput.value = replaceText(299 textInput.value,300 shortcut,301 autotext,302 cursorPosition303 );304 // Thanks to @briantingtc: mock and dispatch dom event when replacing text in input to correct for interactions with a React controlled input.305 textInput.dispatchEvent(new Event('input', {306 'bubbles': true,307 'cancelable': true308 }));309 setCursorPosition(textInput, cursorPosition - shortcut.length + autotext.length);310 }311 // Specific handler for Facebook element replacements312 function replaceTextFacebook(shortcut, autotext, textInput)313 {314 console.log('Domain: Facebook');315 var text;316 var cursorPosition = getCursorPosition(textInput);317 // Check if it is the search bar vs comments318 if (hasParentSelector(textInput, 'div', ['textInput']))319 {320 console.log('facebook search bar');321 var span = textInput.querySelector('span'); // Can only get collection322 if (span) {323 textInput = span;324 }325 // Get text and replace it326 text = textInput.textContent;327 textInput.textContent = replaceText(328 text,329 shortcut,330 autotext,331 cursorPosition332 );333 // Set new cursor position334 setCursorPosition(textInput, cursorPosition - shortcut.length + autotext.length);335 }336 else if (hasParentSelector(textInput,'div', ['UFICommentContainer'])) {337 console.log('facebook comments'); // doesn't work, due to ReactJS framework338 }339 else340 {341 // Get text and replace it342 text = textInput.textContent;343 textInput.textContent = replaceText(344 text,345 shortcut,346 autotext,347 cursorPosition348 );349 // Set new cursor position350 setCursorPosition(textInput,351 cursorPosition - shortcut.length + autotext.length);352 }353 }354 // Specific handler for Basecamp iframe replacements355 function replaceTextBasecamp(shortcut, autotext)356 {357 console.log('Domain: Basecamp');358 // Get the focused / selected text node359 var iframeWindow = document.querySelector(SELECTOR_BASECAMP_EDIT).contentWindow;360 var node = findFocusedNode(iframeWindow);361 console.log('node:', node);362 // Pass onto editable iframe text handler363 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);364 }365 // Specific handler for Outlook iframe replacements366 function replaceTextOutlook(shortcut, autotext)367 {368 console.log('Domain: Outlook');369 // Get the focused / selected text node370 var iframeWindow = document.getElementById(SELECTOR_OUTLOOK_EDIT.substr(1))371 .contentWindow; // Need to cut off the # sign372 var node = findFocusedNode(iframeWindow);373 console.log('node:', node);374 // Pass onto editable iframe text handler375 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);376 }377 // Specific handler for Evernote iframe replacements378 function replaceTextEvernote(shortcut, autotext)379 {380 console.log('Domain: Evernote');381 // Get the focused / selected text node382 var iframeWindow = document.getElementById(SELECTOR_EVERNOTE_EDIT)383 .querySelector('iframe').contentWindow;384 var node = findFocusedNode(iframeWindow);385 console.log('node:', node);386 // Pass onto editable iframe text handler387 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);388 }389 // Specific handler for Google Translate iframe text replacements390 function replaceTextGTT(shortcut, autotext)391 {392 console.log('Domain: Google Translate');393 // Get the focused / selected text node394 var iframeWindow = document.querySelector(SELECTOR_GTT_EDIT)395 .querySelector('iframe').contentWindow;396 var node = findFocusedNode(iframeWindow);397 console.log('node:', node);398 // Pass onto editable iframe text handler399 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);400 }401 // Specific handler for Google Docs iframe text replacements402 function replaceTextGDOCS(shortcut, autotext)403 {404 console.log('Domain: Google Docs');405 // Get the focused / selected text node406 var iframeWindow = document.querySelector(SELECTOR_GDOCS_EDIT).contentWindow;407 var node = findFocusedNode(iframeWindow);408 console.log('node:', node);409 // We can catch the text / event, but we can't seem to replace410 // or dispatch events to create the additional text411 // var e = $.Event('keydown');412 // e.which = 65; // Character 'A'413 // $(node).trigger(e);414 // $(node).trigger(e);415 // $(node).trigger(e);416 // $(node).trigger(e);417 //// Custom logic418 // var textInput = node;419 // console.log(textInput);420 //421 // // Get and process text, update cursor position422 // var text = replaceHTML(node.textContent, shortcut, autotext, 0)423 // , multiline = false424 // , lines425 // ;426 //427 // // If autotext is multiline text, split by newlines, join with <br> tag instead428 // if (autotext.indexOf('\n') >= 0)429 // {430 // lines = text.split('\n');431 // text = lines.join('<br>');432 // multiline = true;433 // }434 //435 // // A way to insert HTML into a content editable div with raw JS.436 // // Creates an element with the HTML content, then transfers node by node437 // // to a new Document Fragment that replaces old node438 // // Source from: http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div439 // var el = document.createElement('div') // Used to store HTML440 // , frag = document.createDocumentFragment() // To replace old node441 // , cursorNode; // To track cursor position442 // el.innerHTML = text; // Set HTML to div, then move to frag443 // for (var tempNode; tempNode = el.firstChild; frag.appendChild(tempNode))444 // {445 // console.log(tempNode.nodeType, tempNode);446 // if (tempNode.nodeType === Node.COMMENT_NODE447 // && tempNode.nodeValue == ATE_CONST.CURSOR_TRACKING_TAG) {448 // cursorNode = tempNode;449 // }450 // }451 // textInput.appendChild(frag); // add fragment of text452 //453 // // Set cursor position based off tracking node (or last child if we454 // // weren't able to find the cursor tracker), then remove tracking node455 // if (cursorNode) {456 // cursorNode.parentNode.removeChild(cursorNode);457 // }458 }459 // Specific handler for Atlassian frame editor text replacements460 function replaceTextAtlassian(shortcut, autotext)461 {462 console.log('Domain: Atlassian');463 // Get the focused / selected text node464 var iframeWindow = document.querySelector(SELECTOR_ATLASSIAN_EDIT).contentWindow;465 var node = findFocusedNode(iframeWindow);466 console.log('node:', node);467 // Pass onto editable iframe text handler468 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);469 }470 // Specific handler for Zendesk Inbox frame editor text replacements471 function replaceTextZendesk(shortcut, autotext)472 {473 console.log('Domain: Zendesk');474 if (document.querySelector(SELECTOR_ZENDESK_INBOX_EDIT)) {475 // Get the focused / selected text node476 var iframeWindow = document.querySelector(SELECTOR_ZENDESK_INBOX_EDIT).contentWindow;477 var node = findFocusedNode(iframeWindow);478 console.log('node:', node);479 // Pass onto editable iframe text handler480 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);481 } else {482 // To make it work with Zendesk's rich text editor483 replaceTextContentEditable(shortcut, autotext, findFocusedNode());484 }485 }486 // Specific handler for CKEditor iframe replacements487 function replaceTextCKE(shortcut, autotext)488 {489 console.log('Editor: CKE');490 // Get the focused / selected text node491 var iframeWindow = document.querySelector(SELECTOR_CKE_EDIT)492 .contentWindow;493 var node = findFocusedNode(iframeWindow);494 console.log('node:', node);495 // Pass onto editable iframe text handler496 replaceTextContentEditable(shortcut, autotext, node, iframeWindow);497 }498 // Reusable handler for editable iframe text replacements499 function replaceTextContentEditable(shortcut, autotext, node, win)500 {501 // Find focused div instead of what's receiving events502 var textInput = node.parentNode;503 console.log(textInput);504 // Get and process text, update cursor position505 var cursorPosition = getCursorPosition(textInput, win)506 , text = replaceHTML(node.textContent, shortcut, autotext, cursorPosition)507 , multiline = false508 , lines509 ;510 // If autotext is multiline text, split by newlines, join with <br> tag instead511 if (autotext.indexOf('\n') >= 0)512 {513 lines = text.split('\n');514 text = lines.join('<br>');515 multiline = true;516 }517 // A way to insert HTML into a content editable div with raw JS.518 // Creates an element with the HTML content, then transfers node by node519 // to a new Document Fragment that replaces old node520 // Source from: http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div521 var el = document.createElement('div') // Used to store HTML522 , frag = document.createDocumentFragment() // To replace old node523 , cursorNode; // To track cursor position524 el.innerHTML = text; // Set HTML to div, then move to frag525 for (var tempNode; tempNode = el.firstChild; frag.appendChild(tempNode))526 {527 console.log(tempNode.nodeType, tempNode);528 if (tempNode.nodeType === Node.COMMENT_NODE529 && tempNode.nodeValue == ATE_CONST.CURSOR_TRACKING_TAG) {530 cursorNode = tempNode;531 }532 }533 textInput.replaceChild(frag, node); // Replace old node with frag534 // Set cursor position based off tracking node (or last child if we535 // weren't able to find the cursor tracker), then remove tracking node536 setCursorPositionAfterNode(cursorNode || textInput.lastChild, win);537 if (cursorNode) {538 cursorNode.parentNode.removeChild(cursorNode);539 }540 }541 // Replacing shortcut with autotext in text at cursorPosition542 function replaceText(text, shortcut, autotext, cursorPosition)543 {544 console.log('cursorPosition:', cursorPosition);545 console.log('currentText:', text);546 console.log('shortcut:', shortcut);547 console.log('expandedText:', autotext);548 // Replace shortcut based off cursorPosition549 return [text.slice(0, cursorPosition - shortcut.length),550 autotext, text.slice(cursorPosition)].join('');551 }552 // Replacing shortcut with autotext HTML content at cursorPosition553 function replaceHTML(text, shortcut, autotext, cursorPosition)554 {555 console.log('cursorPosition:', cursorPosition);556 console.log('currentText:', text);557 console.log('shortcut:', shortcut);558 console.log('expandedText:', autotext);559 // If autotext expansion already has cursor tag in it, don't insert560 var cursorTag = (autotext.indexOf(ATE_CONST.CURSOR_TRACKING_HTML) >= 0)561 ? '' : ATE_CONST.CURSOR_TRACKING_HTML;562 // Replace shortcut based off cursorPosition,563 // insert tracking tag for cursor if it isn't already defined in autotext564 return [text.slice(0, cursorPosition - shortcut.length),565 autotext, cursorTag, text.slice(cursorPosition)].join('');566 }567 // Find node that has text contents that matches text568 function findMatchingTextNode(div, text)569 {570 return $(div).contents().filter(function() {571 return (this.nodeType == Node.TEXT_NODE) // Return all text nodes572 && (this.nodeValue.length == text.length); // with same text length573 }).filter(function() {574 return (this.nodeValue == text); // Filter for same text575 }).first().get(0);576 }577 // Find node that user is editing right now, for editable divs578 // Optional passed window to perform selection find on579 function findFocusedNode(win)580 {581 // Use default window if not given window to search in582 if (!win) {583 win = window;584 }585 // Look for selection586 if (win.getSelection) {587 var selection = win.getSelection();588 if (selection.rangeCount) {589 return selection.getRangeAt(0).startContainer;590 }591 }592 return null;593 }...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

...136 currentA11yTree = await getAccessibilityTree(client);137 electronWinA11yTree.webContents.send('updateA11yTree', JSON.stringify(currentA11yTree, null, 2));138}139// https://stackoverflow.com/a/60958198140function findFocusedNode(node) {141 //console.log('checking node',node);142 /*143 // first web area node was also focused, we have to skip it to find real element144 if (node.focused && node.role != 'WebArea') {145 return node;146 }147 for (const child of node.children || []) {148 const focusedNode = findFocusedNode(child);149 if (focusedNode) {150 return focusedNode;151 }152 }*/153 // current workaround, has a little bit different properties154 // tree with child nodes, all on same hierachy155 if(node.properties !== undefined){156 let focusedPropertyObj = node.properties.find(obj => {157 if(obj.name == 'focused'){158 console.log('Checking obj - we found obj with focused',obj);159 console.log('Checking obj - returning', (obj.name == 'focused' && obj.value.value == true))160 }161 return (obj.name == 'focused' && obj.value.value == true);162 });163 // WebArea is always focused in electron, we skip it164 // TODO: find a better way to skip first element? is it always first element165 if (focusedPropertyObj !== undefined){166 console.log('Found focused property object', focusedPropertyObj,'Node:', node);167 if(node.role.value != 'WebArea'){168 console.log('FOUND SOMETHING, RETURNING', node);169 return node;170 }else{171 console.log('Element skipped, it is the parent WebArea of electron', node);172 }173 }174 }175 for (const child of node.nodes || []) {176 const focusedNode = findFocusedNode(child);177 if (focusedNode) {178 return focusedNode;179 }180 }181}182async function outputAndSpeakCurrentElement(actionType) {183 let currentElementForOutput;184 // tab actions (focusable elements)185 if (actionType == 'focus') {186 /*187 //console.log('Creating snapshot of accessibility tree ...');188 let currentSnapshot = await pptrPage.accessibility.snapshot();189 console.log('Current snapshot', currentSnapshot);190 // we need to go into children, because it is in a WebArea on electron, maybe because of pupeteer-electron191 currentElementForOutput = findFocusedNode(currentSnapshot);192 console.log('Current focused element in WebArea:', currentElementForOutput);*/193 // workaround workflow, save current full tree194 await saveStaticA11yTree();195 // set global focused element196 currentFocusedElement = findFocusedNode(currentA11yTree);197 if(currentFocusedElement != undefined){198 // set global node id199 currentFocusedOrReadNodeId = currentFocusedElement.nodeId;200 console.log('Current focused element in WebArea:', currentFocusedElement, 'nodeId',currentFocusedOrReadNodeId);201 202 // set for speech output203 currentElementForOutput = currentFocusedElement;204 }else{205 // no element focused, maybe after page reload206 // TODO: what should we do?207 return false;208 }209 }210 // read action in static copy a11y tree...

Full Screen

Full Screen

accessibility.spec.js

Source:accessibility.spec.js Github

copy

Full Screen

...101 role: 'text', name: 'hi'102 }]103 }]104 };105 expect(findFocusedNode(await page.accessibility.snapshot({interestingOnly: false}))).toEqual(golden);106 });107 it('roledescription', async({page}) => {108 await page.setContent('<div tabIndex=-1 aria-roledescription="foo">Hi</div>');109 const snapshot = await page.accessibility.snapshot();110 expect(snapshot.children[0].roledescription).toEqual('foo');111 });112 it('orientation', async({page}) => {113 await page.setContent('<a href="" role="slider" aria-orientation="vertical">11</a>');114 const snapshot = await page.accessibility.snapshot();115 expect(snapshot.children[0].orientation).toEqual('vertical');116 });117 it('autocomplete', async({page}) => {118 await page.setContent('<input type="number" aria-autocomplete="list" />');119 const snapshot = await page.accessibility.snapshot();120 expect(snapshot.children[0].autocomplete).toEqual('list');121 });122 it('multiselectable', async({page}) => {123 await page.setContent('<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>');124 const snapshot = await page.accessibility.snapshot();125 expect(snapshot.children[0].multiselectable).toEqual(true);126 });127 it('keyshortcuts', async({page}) => {128 await page.setContent('<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>');129 const snapshot = await page.accessibility.snapshot();130 expect(snapshot.children[0].keyshortcuts).toEqual('foo');131 });132 describe('filtering children of leaf nodes', function() {133 it('should not report text nodes inside controls', async function({page}) {134 await page.setContent(`135 <div role="tablist">136 <div role="tab" aria-selected="true"><b>Tab1</b></div>137 <div role="tab">Tab2</div>138 </div>`);139 const golden = FFOX ? {140 role: 'document',141 name: '',142 children: [{143 role: 'pagetab',144 name: 'Tab1',145 selected: true146 }, {147 role: 'pagetab',148 name: 'Tab2'149 }]150 } : {151 role: 'WebArea',152 name: '',153 children: [{154 role: 'tab',155 name: 'Tab1',156 selected: true157 }, {158 role: 'tab',159 name: 'Tab2'160 }]161 };162 expect(await page.accessibility.snapshot()).toEqual(golden);163 });164 it('rich text editable fields should have children', async function({page}) {165 await page.setContent(`166 <div contenteditable="true">167 Edit this image: <img src="fakeimage.png" alt="my fake image">168 </div>`);169 const golden = FFOX ? {170 role: 'section',171 name: '',172 children: [{173 role: 'text leaf',174 name: 'Edit this image: '175 }, {176 role: 'text',177 name: 'my fake image'178 }]179 } : {180 role: 'GenericContainer',181 name: '',182 value: 'Edit this image: ',183 children: [{184 role: 'text',185 name: 'Edit this image:'186 }, {187 role: 'img',188 name: 'my fake image'189 }]190 };191 const snapshot = await page.accessibility.snapshot();192 expect(snapshot.children[0]).toEqual(golden);193 });194 it('rich text editable fields with role should have children', async function({page}) {195 await page.setContent(`196 <div contenteditable="true" role='textbox'>197 Edit this image: <img src="fakeimage.png" alt="my fake image">198 </div>`);199 const golden = FFOX ? {200 role: 'entry',201 name: '',202 value: 'Edit this image: my fake image',203 children: [{204 role: 'text',205 name: 'my fake image'206 }]207 } : {208 role: 'textbox',209 name: '',210 value: 'Edit this image: ',211 children: [{212 role: 'text',213 name: 'Edit this image:'214 }, {215 role: 'img',216 name: 'my fake image'217 }]218 };219 const snapshot = await page.accessibility.snapshot();220 expect(snapshot.children[0]).toEqual(golden);221 });222 // Firefox does not support contenteditable="plaintext-only".223 !FFOX && describe('plaintext contenteditable', function() {224 it('plain text field with role should not have children', async function({page}) {225 await page.setContent(`226 <div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);227 const snapshot = await page.accessibility.snapshot();228 expect(snapshot.children[0]).toEqual({229 role: 'textbox',230 name: '',231 value: 'Edit this image:'232 });233 });234 it('plain text field without role should not have content', async function({page}) {235 await page.setContent(`236 <div contenteditable="plaintext-only">Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);237 const snapshot = await page.accessibility.snapshot();238 expect(snapshot.children[0]).toEqual({239 role: 'GenericContainer',240 name: ''241 });242 });243 it('plain text field with tabindex and without role should not have content', async function({page}) {244 await page.setContent(`245 <div contenteditable="plaintext-only" tabIndex=0>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);246 const snapshot = await page.accessibility.snapshot();247 expect(snapshot.children[0]).toEqual({248 role: 'GenericContainer',249 name: ''250 });251 });252 });253 it('non editable textbox with role and tabIndex and label should not have children', async function({page}) {254 await page.setContent(`255 <div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox">256 this is the inner content257 <img alt="yo" src="fakeimg.png">258 </div>`);259 const golden = FFOX ? {260 role: 'entry',261 name: 'my favorite textbox',262 value: 'this is the inner content yo'263 } : {264 role: 'textbox',265 name: 'my favorite textbox',266 value: 'this is the inner content '267 };268 const snapshot = await page.accessibility.snapshot();269 expect(snapshot.children[0]).toEqual(golden);270 });271 it('checkbox with and tabIndex and label should not have children', async function({page}) {272 await page.setContent(`273 <div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox">274 this is the inner content275 <img alt="yo" src="fakeimg.png">276 </div>`);277 const golden = FFOX ? {278 role: 'checkbutton',279 name: 'my favorite checkbox',280 checked: true281 } : {282 role: 'checkbox',283 name: 'my favorite checkbox',284 checked: true285 };286 const snapshot = await page.accessibility.snapshot();287 expect(snapshot.children[0]).toEqual(golden);288 });289 it('checkbox without label should not have children', async function({page}) {290 await page.setContent(`291 <div role="checkbox" aria-checked="true">292 this is the inner content293 <img alt="yo" src="fakeimg.png">294 </div>`);295 const golden = FFOX ? {296 role: 'checkbutton',297 name: 'this is the inner content yo',298 checked: true299 } : {300 role: 'checkbox',301 name: 'this is the inner content yo',302 checked: true303 };304 const snapshot = await page.accessibility.snapshot();305 expect(snapshot.children[0]).toEqual(golden);306 });307 });308 function findFocusedNode(node) {309 if (node.focused)310 return node;311 for (const child of node.children || []) {312 const focusedChild = findFocusedNode(child);313 if (focusedChild)314 return focusedChild;315 }316 return null;317 }318 });...

Full Screen

Full Screen

completion.js

Source:completion.js Github

copy

Full Screen

...12const Completion = {};13// ----------------------------------------------------------------------------14Completion.onCompletion = info => {15 const ast = getAst(info);16 const node = findFocusedNode(ast, info.position);17 const triggerCharacter = info.context.triggerCharacter;18 if(!node || Ast.isDeclarationName(node)) { return; }19 if(triggerCharacter === '.') { 20 Analyzer.analyze(ast); // TODO: Do not analyze here21 let propertyAccess = node;22 if(node.kind === ts.SyntaxKind.Identifier) {23 propertyAccess = node.parent;24 } else if(node.kind !== ts.SyntaxKind.PropertyAccessExpression) {25 return ;26 }27 return computePropertyCompletions(propertyAccess);28 } else if(Ast.isNameOfPropertyAccessExpression(node)) {29 return computePropertyCompletions(node.parent);30 } else {...

Full Screen

Full Screen

hover.js

Source:hover.js Github

copy

Full Screen

...14const noInfo = { contents: [] };15// ----------------------------------------------------------------------------16Hover.onHover = info => {17 const ast = getAst(info);18 const node = findFocusedNode(ast, info.position);19 if(!node) { return noInfo; }20 21 switch(node.kind) {22 case ts.SyntaxKind.Constructor:23 return createConstructorInfo(ast, node);24 case ts.SyntaxKind.Identifier:25 return createIdentifierInfo(ast, node);26 default: return noInfo;27 }28 29};30// ----------------------------------------------------------------------------31function createConstructorInfo(ast, node) {32 const parentName = node.parent.name ? node.parent.name.getText(ast) : '';...

Full Screen

Full Screen

definition.js

Source:definition.js Github

copy

Full Screen

...11 * @param {vscodeLanguageServer.DefinitionParams} info 12 */13Definition.onDefinition = info => {14 const ast = getAst(info);15 const node = findFocusedNode(ast, info.position);16 if(!node) { return null; }17 switch(node.kind) {18 case ts.SyntaxKind.Identifier: {19 const symbol = getSymbolOfIdentifier(node);20 if(!symbol || !symbol.declaration) { return ; }21 const sourceFile = symbol.declaration.getSourceFile();22 if(sourceFile === es5LibAst) { return ; }23 const uri = sourceFile.fileName;24 const range = createRange(symbol);25 const location = vscodeLanguageServer.Location.create(uri, range);26 return location;27 }28 default: return null;29 }...

Full Screen

Full Screen

accessibility.js

Source:accessibility.js Github

copy

Full Screen

1const puppeteer = require('puppeteer');2function findFocusedNode(node) {3 if (node.focused)4 return node5 for (const child of node.children || []) {6 const foundNode = findFocusedNode(child);7 if (foundNode)8 return foundNode;9 }10 return null;11}12async function updateSnapshot(page) {13 let snapshot = await page.accessibility.snapshot();14 return findFocusedNode(snapshot);15}16(async () => {17 const browser = await puppeteer.launch({18 // headless: false, 19 // slowMo: 50020 });21 const page = await browser.newPage();22 await page.goto('https://ubuntu.com');23 24 await page.keyboard.press("Enter");25 let snapshot = await page.accessibility.snapshot();26 console.log(snapshot)27 await page.keyboard.press("Tab");28 let n = await updateSnapshot(page);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 const element = await page.$('input[name="q"]');6 await element.type('hello world');7 const focusedElement = await page.evaluateHandle(() => {8 return document.activeElement;9 });10 const nodeName = await focusedElement.evaluate(node => node.nodeName);11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 await page.focus('input[name="q"]');6 const focusedElement = await page.evaluate(() => {7 return document.querySelector(':focus');8 });9 console.log(focusedElement);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const path = require('path');3(async () => {4 const browser = await puppeteer.launch({headless: false});5 const page = await browser.newPage();6 await page.focus('input[name="q"]');7 const nodeHandle = await page.evaluateHandle(() => document.activeElement);8 console.log(await page.evaluate(e => e.nodeName, nodeHandle));9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3const browser = await puppeteer.launch();4const page = await browser.newPage();5await page.focus('input[name="q"]');6const element = await page.findFocusedNode();7console.log(element);8await browser.close();9})();10{11}

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const element = await page.$('input[name="q"]');6 await element.focus();7 const focusedElement = await page.evaluateHandle(() => document.activeElement);8 console.log(focusedElement);9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 const element = await page.$('input[name="q"]');16 await element.focus();17 const focusedElement = await page.evaluateHandle(() => document.activeElement);18 console.log(focusedElement);19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch();24 const page = await browser.newPage();25 const element = await page.$('input[name="q"]');26 await element.focus();27 const focusedElement = await page.evaluateHandle(() => document.activeElement);28 console.log(focusedElement);29 await browser.close();30})();31const puppeteer = require('puppeteer');32(async () => {33 const browser = await puppeteer.launch();34 const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 const focusedElement = await page.evaluate(() => {7 return document.activeElement;8 });9 console.log('Focused element is', focusedElement);10 const focusedElementTagName = await page.evaluate(() => {11 return document.activeElement.tagName;12 });13 console.log('Focused element tag name is', focusedElementTagName);14 const focusedElementClassName = await page.evaluate(() => {15 return document.activeElement.className;16 });17 console.log('Focused element class name is', focusedElementClassName);18 const focusedElementId = await page.evaluate(() => {19 return document.activeElement.id;20 });21 console.log('Focused element id is', focusedElementId);22 const focusedElementTextContent = await page.evaluate(() => {23 return document.activeElement.textContent;24 });25 console.log('Focused element text content is', focusedElementTextContent);26 await browser.close();27})();28const puppeteer = require('puppeteer');29(async () => {30 const browser = await puppeteer.launch({31 });32 const page = await browser.newPage();33 const focusedElement = await page.evaluate(() => {34 return document.activeElement;35 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const mkdir = promisify(fs.mkdir);6const writeFile = promisify(fs.writeFile);7(async () => {8 const browser = await puppeteer.launch({ headless: false });9 const page = await browser.newPage();10 const focusedElement = await page.evaluateHandle(() => document.activeElement);11 const boundingBox = await focusedElement.boundingBox();12 const tagName = await focusedElement.evaluate((el) => el.tagName);13 const textContent = await focusedElement.evaluate((el) => el.textContent);14 const innerHTML = await focusedElement.evaluate((el) => el.innerHTML);15 const outerHTML = await focusedElement.evaluate((el) => el.outerHTML);16 const className = await focusedElement.evaluate((el) => el.className);17 const id = await focusedElement.evaluate((el) => el.id);18 const name = await focusedElement.evaluate((el) => el.name);19 const value = await focusedElement.evaluate((el) => el.value);20 const href = await focusedElement.evaluate((el) => el.href);21 const src = await focusedElement.evaluate((el) => el.src);22 const alt = await focusedElement.evaluate((el) => el.alt);23 const title = await focusedElement.evaluate((el) => el.title);24 const placeholder = await focusedElement.evaluate((el) => el.placeholder);25 const role = await focusedElement.evaluate((el) => el.role);26 const ariaLabel = await focusedElement.evaluate((el) =>

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { exec, execSync } = require('child_process');5(async () => {6 const browser = await puppeteer.launch({7 });8 const page = await browser.newPage();9 await page.waitForSelector('input[name="q"]');10 await page.type('input[name="q"]', 'puppeteer');11 await page.keyboard.press('Enter');12 await page.waitForTimeout(5000);13 const node = await page.findFocusedNode();14 const element = await node.asElement();15 await element.screenshot({ path: 'screenshot.png' });16 await browser.close();17})();

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Puppeteer automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful