Best JavaScript code snippet using playwright-internal
PageAgent.js
Source:PageAgent.js
...395 if (!toPrincipal.subsumes(fromPrincipal))396 return { remoteObject: null };397 return { remoteObject: context.rawValueToRemoteObject(unsafeObject) };398 }399 async _setFileInputFiles({objectId, frameId, files}) {400 const frame = this._frameTree.frame(frameId);401 if (!frame)402 throw new Error('Failed to find frame with id = ' + frameId);403 const unsafeObject = frame.unsafeObject(objectId);404 if (!unsafeObject)405 throw new Error('Object is not input!');406 const nsFiles = await Promise.all(files.map(filePath => File.createFromFileName(filePath)));407 unsafeObject.mozSetFileArray(nsFiles);408 }409 _getContentQuads({objectId, frameId}) {410 const frame = this._frameTree.frame(frameId);411 if (!frame)412 throw new Error('Failed to find frame with id = ' + frameId);413 const unsafeObject = frame.unsafeObject(objectId);...
frametracker.js
Source:frametracker.js
1//2// Track frame nodes as they are added to the DOM.3//4// The main purpose is to find DevTools NodesIds for frames for given selectors / queries.5//6// The NodeIds / frame IDs returned can then be converted to an execution content id via pizza.contexttracker,7// which keeps track of JavaScript context ids.8//9// Provides functions to querying frames in the current DOM.10//11// After the top level document (which itself is a frame), each sub frame has two node ids. One in the parent frame,12// and one in the sub frame itself.13//14// Uses Devtools DOM.* APIs15//16pizza.main.frametracker = function() {17 // Chrome Extension Frame ID to top level document node id for current page18 var _frameIdToContentNodeId = {};19 // Node ID of frame (in context of parent document) to frame details20 var _nodeIdToFrame = {};21 // Node ID of frame (in context of parent document) to Chrome Extension Frame Id22 var _nodeIdToFrameId = {};23 var _rootNodeId = null;24 var _tabId = null;25 var _documentUpdated = function(params) {26 _nodeIdToFrameId = {};27 _nodeIdToFrame = {};28 _frameIdToContentNodeId = {};29 _rootNodeId = null;30 };31 var _processNodeList = function(nodes) {32 for (var i = 0; i < nodes.length; ++i) {33 _processNode(nodes[i]);34 }35 };36 var _processNode = function(node) {37 if (node.frameId && node.nodeId) {38 _nodeIdToFrameId[node.nodeId] = node.frameId;39 _nodeIdToFrame[node.nodeId] = node;40 _frameIdToContentNodeId[node.frameId] = node.contentDocument.nodeId;41 }42 if (node.children) {43 _processNodeList(node);44 }45 };46 var _setChildNodes = function(params) {47 _processNodeList(params.nodes);48 };49 var _getFrameIdForNodeId = function(nodeId) {50 return _nodeIdToFrameId[nodeId];51 };52 var _handleEvent = function(method, params) {53 switch (method) {54 case 'DOM.documentUpdated':55 _documentUpdated(params);56 break;57 case 'DOM.setChildNodes':58 _setChildNodes(params);59 break;60 default:61 // do nothing62 break;63 }64 };65 var _sendCommand = function(cmd, params, respondFunc) {66 params = params || {};67 chrome.debugger.sendCommand({ tabId: _tabId }, cmd, params,68 function (response) {69 if (response) {70 respondFunc(response);71 } else {72 respondFunc({ error: chrome.runtime.lastError });73 }74 });75 };76 var _getRootId = function(callback) {77 if (_rootNodeId) {78 callback(_rootNodeId);79 } else {80 _sendCommand('DOM.getDocument', {}, function(response) {81 console.log(response);82 if (response.root) {83 console.log("rootId", response.root.nodeId);84 _rootNodeId = response.root.nodeId;85 callback(_rootNodeId);86 } else {87 callback(null, response.error)88 }89 });90 }91 };92 var _copyAttributes = function(dest, props, src) {93 for (var i = 0; i < src.length; i += 2) {94 var val = src[i];95 if (props.indexOf(val) > 0) {96 dest[val] = src[i+1];97 }98 }99 };100 var _resolveFrameNode = function(nodeId, callback) {101 _sendCommand('DOM.resolveNode', { nodeId: nodeId }, function(response) {102 if (response.error) {103 callback( { error: response.error });104 } else {105 _sendCommand('DOM.requestNode', { objectId: response.object.objectId }, function(response) {106 var frameId = _nodeIdToFrameId[nodeId];107 if (frameId) {108 var r = _nodeIdToFrame[nodeId];109 var value = {110 type: r.localName,111 frameId: r.frameId112 };113 _copyAttributes(value,114 ["id", "name", "src", "width", "height", "style", "title"],115 r.attributes);116 callback({ value: value });117 } else {118 callback({ error: "No frames matching selector" });119 }120 });121 }122 });123 };124 var _resolveFrameNodes = function(nodeIds, callback) {125 var wait = pizza.waitAll();126 var elements = [];127 var errors = [];128 for (var i = 0; i < nodeIds.length; ++i) {129 _resolveFrameNode(nodeIds[i], wait.add(function(response) {130 if (response.value) {131 elements.push(response.value);132 } else if (response.error) {133 errors.push(response.error);134 }135 }));136 }137 wait.done(function() {138 var response = {};139 if (elements.length > 0) {140 response.value = elements;141 } else if (errors.length > 0) {142 response.error = errors;143 } else {144 response.value = [];145 }146 callback(response);147 });148 };149 var _resolveFrame = function(frameId, callback) {150 var foundNodeId = null;151 for (var nodeId in _nodeIdToFrameId) {152 if (_nodeIdToFrameId[nodeId] === frameId) {153 console.log("matched", nodeId, frameId);154 foundNodeId = nodeId;155 break;156 }157 }158 _sendCommand('DOM.resolveNode', { nodeId: parseInt(foundNodeId) }, callback);159 };160 var _listFramesForNode = function(selector, nodeId, callback) {161 _sendCommand('DOM.querySelectorAll', { nodeId: nodeId, selector: selector }, function(response) {162 if (response.nodeIds) {163 _resolveFrameNodes(response.nodeIds, callback);164 } else {165 callback({ error: "Element not found for selector: " + selector });166 }167 });168 };169 var _queryFramesNoOffset = function(selector, frameId, callback) {170 if (frameId) {171 _listFramesForNode(selector, _frameIdToContentNodeId[frameId], callback);172 } else {173 _getRootId(function(rootId) {174 _listFramesForNode(selector, rootId, callback);175 });176 }177 };178 var _splitOnSpacesWithEscapes = function(str) {179 var a = [];180 var start = 0;181 for (var i = 0; i < str.length; ++i) {182 var c = str.charAt(i);183 if (c === '\\') {184 ++i;185 } else if (c == ' ') {186 a.push(str.substring(start, i));187 start = i;188 }189 }190 if (str.length != 0) {191 a.push(str.substring(start));192 }193 return a;194 };195 var _parseIndexFromSelector = function(selector) {196 var m = selector.match(/^(.*):(eq|nth)\((\d+)\)$/);197 if (m) {198 return { css: m[1], index: Number(m[3]) };199 }200 return { css: selector, index: -1 };201 };202 var _queryFrameFrameSelector = function(selector, frameId, callback) {203 var selectorArray = _splitOnSpacesWithEscapes(selector);204 if (selectorArray.length === 0) {205 callback({ error: "zero length selector" });206 }207 var frame = null;208 var search = function(nodeId, i, callback) {209 var sel = _parseIndexFromSelector(selectorArray[i]);210 _sendCommand('DOM.querySelectorAll',211 { nodeId: nodeId, selector: sel.css },212 function(response) {213 if (response.nodeIds) {214 _resolveFrameNodes(response.nodeIds, function (response) {215 if (!response.value) {216 callback();217 }218 if (sel.index > -1) {219 if (response.value.length > sel.index) {220 response.value = [response.value[sel.index]];221 }222 }223 i++;224 if (i >= selectorArray.length && response.value.length > 0) {225 if (frame == null) {226 frame = response.value[0];227 }228 callback();229 } else {230 async.each(response.value, function (value, callback) {231 search(_frameIdToContentNodeId[value.frameId], i, callback);232 }, function (r) {233 callback(r);234 });235 }236 });237 } else {238 callback({ error: response });239 }240 });241 };242 var respondWithResults = function(err) {243 if (err) {244 callback({ error: err });245 } else if (!frame) {246 callback({ error: "no frame matching selector" });247 } else {248 callback({ value: frame })249 }250 };251 if (frameId) {252 search(_frameIdToContentNodeId[frameId], 0, respondWithResults);253 } else {254 _getRootId(function(rootId) {255 search(rootId, 0, respondWithResults);256 });257 }258 };259 var _queryFrame = function(selector, frameId, callback) {260 var sel = _parseIndexFromSelector(selector);261 // If there's no index on the selector, just pick the first one262 if (sel.index < 0) {263 sel.index = 0;264 }265 _queryFramesNoOffset(sel.css, frameId, function(response) {266 if (response.value) {267 if (response.value.length > sel.index) {268 var frame = response.value[sel.index];269 callback({ value: frame });270 } else {271 callback({ error: "frame index out of bounds, found only " + response.value.length });272 }273 } else {274 callback(response);275 }276 });277 };278 var _queryFrames = function(selector, frameId, callback) {279 var sel = _parseIndexFromSelector(selector);280 _queryFramesNoOffset(sel.css, frameId, function(response) {281 if (response.value) {282 if (sel.index === -1) {283 callback(response);284 } else if (response.value.length > sel.index) {285 var frame = response.value[sel.index];286 callback({ value: [frame] });287 } else {288 callback({ error: "frame index out of bounds, found only " + response.value.length });289 }290 } else {291 callback(response);292 }293 });294 };295 var _queryFramesRecursive = function(selector, nodeId, callback) {296 var wait = pizza.waitAll();297 var errors = [];298 var querySelector = function(nodeId, parent) {299 _sendCommand('DOM.querySelectorAll',300 { nodeId: nodeId, selector: selector },301 wait.add(function(response) {302 if (response.nodeIds) {303 var nodeIds = response.nodeIds;304 if (nodeIds.length === 0) {305 return;306 }307 var elements = null;308 if (parent instanceof Array) {309 elements = parent;310 } else {311 parent.frames = [];312 elements = parent.frames;313 }314 for (var i = 0; i < nodeIds.length; ++i) {315 _resolveFrameNode(nodeIds[i], wait.add(function(response) {316 if (response.value) {317 elements.push(response.value);318 querySelector(_frameIdToContentNodeId[response.value.frameId], response.value);319 } else if (response.error) {320 errors.push(response.error);321 }322 }));323 }324 } else {325 errors.push({ error: "Elements not found for selector: " + selector });326 }327 }));328 };329 var elements = [];330 querySelector(nodeId, elements);331 wait.done(function() {332 var response = {};333 if (elements.length > 0) {334 response.value = elements;335 } else if (errors.length > 0) {336 response.error = errors;337 } else {338 response.value = [];339 }340 callback(response);341 });342 };343 var _highlight = function(objectId, color, callback) {344 _getRootId(function(rootId) {345 _sendCommand('DOM.requestNode', { objectId: objectId }, function(response) {346 var borderColor = { r: 0, g: 0, b: 0 };347 _sendCommand('DOM.highlightNode',348 { nodeId: response.nodeId,349 highlightConfig:350 { showInfo: true,351 contentColor: color,352 borderColor: borderColor,353 marginColor: borderColor } },354 function(response) { callback(response); });355 });356 });357 };358 var _clearHighlight = function() {359 _sendCommand('DOM.hideHighlight', {}, function() {});360 };361 var _setFileInputFiles = function(objectId, files, callback) {362 _getRootId(function(rootId) {363 _sendCommand('DOM.requestNode', { objectId: objectId },364 function(response) {365 _sendCommand('DOM.setFileInputFiles',366 { nodeId: response.nodeId,367 files: files },368 function (result) {369 callback(result);370 });371 });372 });373 };374 var _queryAllFrames = function(selector, callback) {375 _getRootId(function(rootId) {376 _queryFramesRecursive(selector, rootId, callback);377 });378 };379 var _setTab = function(tabId) {380 _tabId = tabId;381 };382 return {383 handleEvent: _handleEvent,384 getFrameIdForNodeId: _getFrameIdForNodeId,385 queryFrame: _queryFrame,386 queryFrameFrameSelector: _queryFrameFrameSelector,387 queryFrames: _queryFrames,388 queryAllFrames: _queryAllFrames,389 highlight: _highlight,390 clearHighlight: _clearHighlight,391 setFileInputFiles: _setFileInputFiles,392 resolveFrame: _resolveFrame,393 setTab: _setTab394 };...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('#iframeResult');7 const frame = page.frame({ name: 'iframeResult' });8 const input = await frame.$('input[type=file]');9 await input._setFileInputFiles('C:\\Users\\myuser\\Desktop\\test.txt');10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.waitForSelector('#iframeResult');19 const frame = page.frame({ name: 'iframeResult' });20 const input = await frame.$('input[type=file]');21 await input._setFileInputFiles('C:\\Users\\myuser\\Desktop\\test.txt');22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.waitForSelector('#iframeResult');31 const frame = page.frame({ name: 'iframeResult' });32 const input = await frame.$('input[type=file]');33 await input._setFileInputFiles('C:\\Users\\myuser\\Desktop\\test.txt');34 await page.screenshot({ path: `example.png` });35 await browser.close();36})();37const {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('input[type="file"]');7 const input = await page.$('input[type="file"]');8 await input._setFileInputFiles('C:\\Users\\user\\Desktop\\test.txt');9 await page.click('input[type="submit"]');10 await page.waitForSelector('pre');11 const text = await page.$eval('pre', (ele) => ele.textContent);12 console.log(text);13 await browser.close();14})();15{"file":"C:\\\\fakepath\\\\test.txt","size":8,"type":"text/plain"}
Using AI Code Generation
1const { _setFileInputFiles } = require('playwright/lib/server/chromium/crPage');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.waitForSelector('#iframeResult');8 const iframe = page.frames().find(frame => frame.url().includes('tryhtml5_input_type_file'));9 const element = await iframe.$('input[type="file"]');10 await _setFileInputFiles(element, ['/Users/username/Desktop/test.txt']);11 await page.close();12 await context.close();13 await browser.close();14})();
Using AI Code Generation
1const { _setFileInputFiles } = require('@playwright/test/lib/server/chromium/crPage');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.waitForSelector('iframe');8 const frame = page.frame({ name: 'iframeResult' });9 const fileInput = await frame.$('input[type="file"]');10 await _setFileInputFiles(fileInput, ['/Users/username/path/to/file.txt']);11 await frame.click('input[type="submit"]');12 await browser.close();13})();14const { test, expect } = require('@playwright/test');15test('should upload file', async ({ page }) => {16 await page.waitForSelector('iframe');17 const frame = page.frame({ name: 'iframeResult' });18 const fileInput = await frame.$('input[type="file"]');19 await fileInput.setInputFiles('/Users/username/path/to/file.txt');20 await frame.click('input[type="submit"]');21 expect(await frame.innerText('#demo')).toBe('File(s) uploaded!');22});
Using AI Code Generation
1const path = require('path');2const { chromium } = require('playwright');3const { _setFileInputFiles } = require('playwright/lib/server/chromium/crPage');4(async () => {5 const browser = await chromium.launch();6 const page = await browser.newPage();7 await page.waitForSelector('#iframeResult');8 const frame = page.frames().find(f => f.url().includes('tryhtml5_input_type_file'));9 await frame.waitForSelector('input[type=file]');10 await _setFileInputFiles(frame, 'input[type=file]', [path.join(__dirname, 'test.txt')]);11 await page.screenshot({ path: 'example.png' });12 await browser.close();13})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const fileChooser = await page.waitForFileChooser();6 await fileChooser._setFileInputFiles('./test.txt');7 await browser.close();8})();
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2const { _setFileInputFiles } = require('@playwright/test/lib/server/frames');3test('test', async ({ page }) => {4 const input = await page.$('#file-upload');5 await _setFileInputFiles(page, input, ['a.png', 'b.png']);6 await page.click('#file-submit');7 expect(await page.$eval('#uploaded-files', el => el.textContent)).toBe('a.png, b.png');8});9const { test, expect } = require('@playwright/test');10test('test', async ({ page }) => {11 await page.setInputFiles('#file-upload', ['a.png', 'b.png']);12 await page.click('#file-submit');13 expect(await page.$eval('#uploaded-files', el => el.textContent)).toBe('a.png, b.png');14});
Using AI Code Generation
1const { _setFileInputFiles } = require('playwright/lib/client/helper');2const fs = require('fs');3const path = require('path');4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 await page.waitForSelector('#iframeResult');9 const frame = page.frame({ name: 'iframeResult' });10 await frame.waitForSelector('#myFile');11 const element = await frame.$('#myFile');12 await _setFileInputFiles(element, [path.join(__dirname, 'test.txt')]);13 await frame.click('#myBtn');14 await page.waitForSelector('#demo');15 const content = await page.textContent('#demo');16 console.log(content);17 await browser.close();18})();
Using AI Code Generation
1const { _setFileInputFiles } = require('playwright/lib/server/injected/injectedScript');2const { getTestState } = require('playwright/lib/server/test');3const { FileChooser } = require('playwright/lib/server/chromium/fileChooser');4const { ElementHandle } = require('playwright/lib/server/dom/elementHandler');5const { Page } = require('playwright/lib/server/chromium/page');6const { Frame } = require('playwright/lib/server/chromium/frame');7const { JSHandle } = require('playwright/lib/server/jsHandle');8const path = require('path');9const filePath = path.resolve(__dirname, 'test.pdf');10const testState = getTestState();11const page = testState.page;12const frame = page.mainFrame();13const fileInput = await frame.$('input[type="file"]');14const fileChooser = new FileChooser(page, 'input[type="file"]');15await _setFileInputFiles(fileInput, fileChooser, [filePath]);16const { _setFileInputFiles } = require('playwright/lib/server/injected/injectedScript');17const { getTestState } = require('playwright/lib/server/test');18const { FileChooser } = require('playwright/lib/server/chromium/fileChooser');19const { ElementHandle } = require('playwright/lib/server/dom/elementHandler');20const { Page } = require('playwright/lib/server/chromium/page');21const { Frame } = require('playwright/lib/server/chromium/frame');22const { JSHandle } = require('playwright/lib/server/jsHandle');23const path = require('path');24const filePath = path.resolve(__dirname, 'test.pdf');25const testState = getTestState();26const page = testState.page;27const frame = page.mainFrame();28const fileInput = await frame.$('input[type="file"]');29const fileChooser = new FileChooser(page, 'input[type="file"]');
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!!