Best JavaScript code snippet using playwright-internal
goalAttachment.js
Source: goalAttachment.js
1var atts = new Array(); // global array of attachments, one for each unique PAEMPGOAL record2var multipleAtts = new Array();3var fromRefreshForm = false;4var fromFirstRefresh = false;5var calledGetAttachment = false;6var attachFrame;7var func1 = null;8var actionGlobal = null;9function evalOpenView(funcToCall)10{11 if(func1 != null) {12 var tempStore = func1;13 func1 = null;14 eval(tempStore);15 }16}17function refreshForm(prodline,company, employee, seqNbr)18{19 if(actionGlobal == "D") {20 evalOpenView(func1);21 actionGlobal = null;22 }23 fromRefreshForm = true;24 var goalform = right.document.forms["goalform"];25 getAttachment(prodline, company, employee, seqNbr, "jsreturn2");26}27function getAttachment(prodline, company, employee, seqNbr, frameStr)28{29 frameStr = (frameStr) ? frameStr : "jsreturn2";30 var attachObj = new GETATTACHObject(prodline,"PAEMPGOAL");31 attachObj.index = "PGOSET1";32 attachObj.rectype = "C"; // comment attachment33 attachObj.key = "K1=" + escape(company) + "&K2=" + escape(employee) + "&K3=" + escape(seqNbr);34 attachObj.out = "JS";35 attachObj.opm = "T";36 attachObj.data = "TRUE";37 attachObj.stat = "TRUE";38 attachObj.header = "TRUE";39 //attachObj.encode = "TEXT";40 attachObj.debug = false;41 if(fromFirstRefresh){42 attachObj.func = "refreshFirstAttachment";43 fromFirstRefresh = false;44 }45 else {46 attachObj.func = "refreshAttachment";47 }48 GETATTACH(attachObj,frameStr);49}50function writeAttachment(cmtObj, prodline, company, employee, seqNbr, action, frameStr)51{52 frameStr = (frameStr) ? frameStr : "jsreturn";53 var attachObj = new WRITEATTACHObject(prodline,"PAEMPGOAL");54 attachObj.index = "PGOSET1";55 attachObj.rectype = "C"; // comment attachment56 attachObj.key = "K1=" + escape(company) + "&K2=" + escape(employee) + "&K3=" + escape(seqNbr);57 attachObj.out = "JS";58 attachObj.opm = (action == "D") ? "D" : "M";59 attachObj.usertype = cmtObj.getUserType();60 if (action != "A" && cmtObj.getRecKey() != null && cmtObj.getSeqKey() != null)61 {62 // modify this record63 attachObj.reckey = escape(cmtObj.getRecKey(),1);64 attachObj.seqkey = escape(cmtObj.getSeqKey(),1);65 }66 if (action != "D")67 {68 attachObj.title = escape(cmtObj.getTitle(),1);69 attachObj.body = escape(cmtObj.getText(),1);70 }71 attachObj.data = "TRUE";72 //attachObj.encode = "TEXT";73 attachObj.debug = false;74 actionGlobal = action;75 //Might be uneeded to do a refresh Attachment on a write76 if(attachObj.usertype == "C") {77 attachObj.func = (action == "D") ? "refreshForm" : "refreshAttachment";78 }79 else {80 fromFirstRefresh = true;81 attachObj.func = (action == "D") ? "refreshForm" : "refreshFirstAttachment";82 }83 WRITEATTACH(attachObj,frameStr);84}85function zeroPad(nbr, lgth)86{87 nbr = nbr.toString();88 for (var i=nbr.length; i<Number(lgth); i++)89 nbr = "0" + nbr;90 return nbr;91}92function highlightFieldInError(fldNm) {93 try {94 var formData = self.right.document.forms["goalform"];95 fldNm = fldNm.toString().toUpperCase();96 if (fldNm.indexOf("PGO-OBJECTIVE") >= 0)97 {98 fldObj = formData.elements["objective"];99 setRequiredField(fldObj);100 fldObj.focus();101 fldObj.select();102 } 103 else if (fldNm.indexOf("PGO-PRIORITY") >= 0)104 {105 fldObj = formData.elements["priority"];106 setRequiredField(fldObj);107 fldObj.focus();108 fldObj.select();109 } 110 else if (fldNm.indexOf("PGO-START-DATE") >= 0)111 {112 fldObj = formData.elements["startDate"];113 setRequiredField(fldObj);114 fldObj.focus();115 fldObj.select();116 } 117 else if (fldNm.indexOf("PGO-END-DATE") >= 0)118 {119 fldObj = formData.elements["endDate"];120 setRequiredField(fldObj);121 fldObj.focus();122 fldObj.select();123 }124 else if (fldNm.indexOf("PGO-PCT-COMPLETED") >= 0)125 {126 fldObj = formData.elements["pctComplete"];127 setRequiredField(fldObj);128 fldObj.focus();129 fldObj.select();130 }131 else if (fldNm.indexOf("PGO-COMPLETE-DATE") >= 0)132 {133 fldObj = formData.elements["completeDate"];134 setRequiredField(fldObj);135 fldObj.focus();136 fldObj.select();137 }138 } catch(e) {}139}140function updateDetailedDesc(prodline, company, employee, seqNbr, funcIncoming, userType)141{142 if (self.lawheader.abort == true) {143 highlightFieldInError(self.lawheader.gfldnbr);144 isUpdating = false;145 //stay on current edit screen146 return;147 }148 (seqNbr == 0) ? seqNbr = self.lawheader.currentSeqNbr: '';149 (funcIncoming) ? func1 = funcIncoming : '';150 var goalform = right.document.forms["goalform"];151 var co = zeroPad(company,4);152 var ee = zeroPad(employee,9);153 var seq = zeroPad(seqNbr,4);154 var parentKey = "K1=" + co + "&K2=" + ee + "&K3=" + seq;155 var attachText;156 var oCmt = new cmtAttach();157 if(userType == "P") {158 attachText = goalform.detailedDesc.value;159 oCmt.setTitle("GoalView Detailed Description"); // <-- use the short 30 character detailedDesc here160 oCmt.setUserType("P");161 }162 else {163 attachText = goalform.compComments.value;164 oCmt.setTitle("GoalView Completion Comments"); // <-- use the short 30 character detailedDesc here165 oCmt.setUserType("C");166 }167 if (attachText.indexOf("%0D%0A") == -1 && attachText.indexOf("%0A") != -1) {168 attachText = attachText.replace(/%0A/g,"%0D%0A");169 }170 // is this an add or a modification?171 // already exists, and attempting change172 if (atts[0] && (userType == "C"))173 {174 // change175 atts[0].setText(unescape(attachText));176 viewFlag = true;177 if(unescape(attachText) == ''){178 writeAttachment(atts[0], prodline, co, ee, seq, "D", "jsreturn");179 atts[0] = null;180 }181 else {182 writeAttachment(atts[0], prodline, co, ee, seq, "M", "jsreturn");183 }184 }185 else if (atts[1] && (userType == "P")) {186 // change187 atts[1].setText(unescape(attachText));188 viewFlag = true;189 if(unescape(attachText) == ''){190 writeAttachment(atts[1], prodline, co, ee, seq, "D", "jsreturn");191 atts[1] = null;192 }193 else {194 writeAttachment(atts[1], prodline, co, ee, seq, "M", "jsreturn");195 }196 }197 else198 {199 // add200 oCmt.setText(unescape(attachText));201 viewflag = true;202 writeAttachment(oCmt, prodline, co, ee, seq, "A", "jsreturn");203 }204}205function refreshFirstAttachment()206{207 fromFirstRefresh = false;208 attachFrame = self.jsreturn2;209 var goalform = right.document.forms["goalform"];210 var attachTextP = goalform.detailedDesc.value;211 if (attachFrame.CmtRec && attachFrame.CmtRec.length)212 {213 var lookingForP = "P";214 for(t=0;t<attachFrame.CmtRec.length;t++) {215 if(attachFrame.CmtRec[t].UserType == "P" && lookingForP == "P") {216 //attachTextP = doTextAttach(attachFrame.CommentData[t].join(""));217 addToArr(1,t,attachTextP, attachFrame);218 lookingForP = "";219 }220 }221 }222 // set the attachment text in the textarea223 goalform.detailedDesc.value = unescape(unescape(attachTextP));224 if(fromRefreshForm == true) {225 setTimeout(function(){document.getElementById("right").style.visibility = "visible";}, 100);226 //removeWaitAlert();227 fromRefreshForm = false;228 }229 evalOpenView(func1);230}231function refreshAttachment()232{233 // initial loading of attachments234 attachFrame = self.jsreturn2;235 var goalform = right.document.forms["goalform"];236 var attachTextP = goalform.detailedDesc.value;237 var attachTextC = goalform.compComments.value;238 // Initially set to null to prevent carryover from diff records239 atts[0] = null;240 atts[1] = null;241 if (attachFrame.CmtRec && attachFrame.CmtRec.length)242 {243 var lookingForC = "C";244 var lookingForP = "P";245 for(t=0;t<attachFrame.CmtRec.length;t++) {246 if(attachFrame.CmtRec[t].UserType == "C" && lookingForC == "C") {247 attachTextC = doTextAttach(attachFrame.CommentData[t].join(""));248 addToArr(0,t,attachTextC, attachFrame);249 lookingForC = "";250 }251 if(attachFrame.CmtRec[t].UserType == "P" && lookingForP == "P") {252 attachTextP = doTextAttach(attachFrame.CommentData[t].join(""));253 addToArr(1,t,attachTextP, attachFrame);254 lookingForP = "";255 }256 }257 }258 // set the attachment text in the textarea259 goalform.detailedDesc.value = unescape(unescape(attachTextP));260 goalform.compComments.value = unescape(unescape(attachTextC));261 if(fromRefreshForm == true) {262 setTimeout(function(){document.getElementById("right").style.visibility = "visible";}, 100);263 //removeWaitAlert();264 fromRefreshForm = false;265 }266 evalOpenView(func1);267}268function cmtAttach()269{270 this.title = null;271 this.text = null;272 this.modifiedDate = null;273 this.modifiedTime = null;274 this.userType = null;275 this.recKey = null;276 this.seqKey = null;277 this.parentKey = null;278}279cmtAttach.prototype.getTitle = function()280{281 return this.title;282}283cmtAttach.prototype.setTitle = function(t)284{285 this.title = t;286}287cmtAttach.prototype.getText = function()288{289 return this.text;290}291cmtAttach.prototype.setText = function(t)292{293 this.text = t;294}295cmtAttach.prototype.getModifiedDate = function()296{297 return this.modifiedDate;298}299cmtAttach.prototype.setModifiedDate = function(d)300{301 this.modifiedDate = d;302}303cmtAttach.prototype.getModifiedTime = function()304{305 return this.modifiedTime;306}307cmtAttach.prototype.setModifiedTime = function(t)308{309 this.modifiedTime = t;310}311cmtAttach.prototype.getUserType = function()312{313 return this.userType;314}315cmtAttach.prototype.setUserType = function(u)316{317 this.userType = u;318}319cmtAttach.prototype.getRecKey = function()320{321 return this.recKey;322}323cmtAttach.prototype.setRecKey = function(r)324{325 this.recKey = r;326}327cmtAttach.prototype.getSeqKey = function()328{329 return this.seqKey;330}331cmtAttach.prototype.setSeqKey = function(s)332{333 this.seqKey = s;334}335cmtAttach.prototype.getParentKey = function()336{337 return this.parentKey;338}339cmtAttach.prototype.setParentKey = function(p)340{341 this.parentKey = p;342}343// Extract a parameter value from a string.344function getVarFromString(varName, str, delim)345{346 var url = str;347 var ptr = url.indexOf(varName + "=");348 var ptr2;349 var val1 = "";350 var delim = (delim) ? delim : "&";351 if (ptr != -1)352 {353 var val1 = url.substring(ptr + varName.length + 1,url.length);354 var ptr2;355 if ((ptr2 = val1.indexOf(delim)) != -1)356 {357 if (ptr2 == -1)358 ptr2 = val1.length;359 val1 = val1.substring(0,ptr2);360 }361 }362 return val1;363}364function doTextAttach(textObj) {365 var attachText366 attachText = textObj;367 if (attachText.indexOf("%0D%0A") == -1 && attachText.indexOf("%0A") != -1) {368 attachText = attachText.replace(/%0A/g,"%0D%0A");369 }370 return attachText;371}372function addToArr(arrIndex, attachIndex, text, attachFrame) {373 var oCmt = new cmtAttach();374 oCmt.setTitle(attachFrame.CmtRec[attachIndex].Title);375 oCmt.setText(text);376 oCmt.setModifiedDate(attachFrame.CmtAttrib[attachIndex].ModifyDate);377 oCmt.setModifiedTime(attachFrame.CmtAttrib[attachIndex].ModifyTime);378 oCmt.setUserType(attachFrame.CmtRec[attachIndex].UserType);379 oCmt.setRecKey(attachFrame.CmtRec[attachIndex].RecKey);380 oCmt.setSeqKey(attachFrame.CmtRec[attachIndex].SeqKey);381 oCmt.setParentKey(attachFrame.CmtParentKey[attachIndex]);382 atts[arrIndex] = oCmt;...
frame.spec.js
Source: frame.spec.js
...20 const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;21 describe('Frame.executionContext', function() {22 it('should work', async({page, server}) => {23 await page.goto(server.EMPTY_PAGE);24 await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);25 expect(page.frames().length).toBe(2);26 const [frame1, frame2] = page.frames();27 const context1 = await frame1.executionContext();28 const context2 = await frame2.executionContext();29 expect(context1).toBeTruthy();30 expect(context2).toBeTruthy();31 expect(context1 !== context2).toBeTruthy();32 expect(context1.frame()).toBe(frame1);33 expect(context2.frame()).toBe(frame2);34 await Promise.all([35 context1.evaluate(() => window.a = 1),36 context2.evaluate(() => window.a = 2)37 ]);38 const [a1, a2] = await Promise.all([39 context1.evaluate(() => window.a),40 context2.evaluate(() => window.a)41 ]);42 expect(a1).toBe(1);43 expect(a2).toBe(2);44 });45 });46 describe('Frame.evaluateHandle', function() {47 it('should work', async({page, server}) => {48 await page.goto(server.EMPTY_PAGE);49 const mainFrame = page.mainFrame();50 const windowHandle = await mainFrame.evaluateHandle(() => window);51 expect(windowHandle).toBeTruthy();52 });53 });54 describe('Frame.evaluate', function() {55 it_fails_ffox('should throw for detached frames', async({page, server}) => {56 const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);57 await utils.detachFrame(page, 'frame1');58 let error = null;59 await frame1.evaluate(() => 7 * 8).catch(e => error = e);60 expect(error.message).toContain('Execution Context is not available in detached frame');61 });62 });63 describe('Frame Management', function() {64 it('should handle nested frames', async({page, server}) => {65 await page.goto(server.PREFIX + '/frames/nested-frames.html');66 expect(utils.dumpFrames(page.mainFrame())).toEqual([67 'http://localhost:<PORT>/frames/nested-frames.html',68 ' http://localhost:<PORT>/frames/two-frames.html (2frames)',69 ' http://localhost:<PORT>/frames/frame.html (uno)',70 ' http://localhost:<PORT>/frames/frame.html (dos)',71 ' http://localhost:<PORT>/frames/frame.html (aframe)'72 ]);73 });74 it('should send events when frames are manipulated dynamically', async({page, server}) => {75 await page.goto(server.EMPTY_PAGE);76 // validate frameattached events77 const attachedFrames = [];78 page.on('frameattached', frame => attachedFrames.push(frame));79 await utils.attachFrame(page, 'frame1', './assets/frame.html');80 expect(attachedFrames.length).toBe(1);81 expect(attachedFrames[0].url()).toContain('/assets/frame.html');82 // validate framenavigated events83 const navigatedFrames = [];84 page.on('framenavigated', frame => navigatedFrames.push(frame));85 await utils.navigateFrame(page, 'frame1', './empty.html');86 expect(navigatedFrames.length).toBe(1);87 expect(navigatedFrames[0].url()).toBe(server.EMPTY_PAGE);88 // validate framedetached events89 const detachedFrames = [];90 page.on('framedetached', frame => detachedFrames.push(frame));91 await utils.detachFrame(page, 'frame1');92 expect(detachedFrames.length).toBe(1);93 expect(detachedFrames[0].isDetached()).toBe(true);94 });95 it('should send "framenavigated" when navigating on anchor URLs', async({page, server}) => {96 await page.goto(server.EMPTY_PAGE);97 await Promise.all([98 page.goto(server.EMPTY_PAGE + '#foo'),99 utils.waitEvent(page, 'framenavigated')100 ]);101 expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');102 });103 it('should persist mainFrame on cross-process navigation', async({page, server}) => {104 await page.goto(server.EMPTY_PAGE);105 const mainFrame = page.mainFrame();106 await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');107 expect(page.mainFrame() === mainFrame).toBeTruthy();108 });109 it('should not send attach/detach events for main frame', async({page, server}) => {110 let hasEvents = false;111 page.on('frameattached', frame => hasEvents = true);112 page.on('framedetached', frame => hasEvents = true);113 await page.goto(server.EMPTY_PAGE);114 expect(hasEvents).toBe(false);115 });116 it('should detach child frames on navigation', async({page, server}) => {117 let attachedFrames = [];118 let detachedFrames = [];119 let navigatedFrames = [];120 page.on('frameattached', frame => attachedFrames.push(frame));121 page.on('framedetached', frame => detachedFrames.push(frame));122 page.on('framenavigated', frame => navigatedFrames.push(frame));123 await page.goto(server.PREFIX + '/frames/nested-frames.html');124 expect(attachedFrames.length).toBe(4);125 expect(detachedFrames.length).toBe(0);126 expect(navigatedFrames.length).toBe(5);127 attachedFrames = [];128 detachedFrames = [];129 navigatedFrames = [];130 await page.goto(server.EMPTY_PAGE);131 expect(attachedFrames.length).toBe(0);132 expect(detachedFrames.length).toBe(4);133 expect(navigatedFrames.length).toBe(1);134 });135 it('should support framesets', async({page, server}) => {136 let attachedFrames = [];137 let detachedFrames = [];138 let navigatedFrames = [];139 page.on('frameattached', frame => attachedFrames.push(frame));140 page.on('framedetached', frame => detachedFrames.push(frame));141 page.on('framenavigated', frame => navigatedFrames.push(frame));142 await page.goto(server.PREFIX + '/frames/frameset.html');143 expect(attachedFrames.length).toBe(4);144 expect(detachedFrames.length).toBe(0);145 expect(navigatedFrames.length).toBe(5);146 attachedFrames = [];147 detachedFrames = [];148 navigatedFrames = [];149 await page.goto(server.EMPTY_PAGE);150 expect(attachedFrames.length).toBe(0);151 expect(detachedFrames.length).toBe(4);152 expect(navigatedFrames.length).toBe(1);153 });154 it('should report frame from-inside shadow DOM', async({page, server}) => {155 await page.goto(server.PREFIX + '/shadow.html');156 await page.evaluate(async url => {157 const frame = document.createElement('iframe');158 frame.src = url;159 document.body.shadowRoot.appendChild(frame);160 await new Promise(x => frame.onload = x);161 }, server.EMPTY_PAGE);162 expect(page.frames().length).toBe(2);163 expect(page.frames()[1].url()).toBe(server.EMPTY_PAGE);164 });165 it('should report frame.name()', async({page, server}) => {166 await utils.attachFrame(page, 'theFrameId', server.EMPTY_PAGE);167 await page.evaluate(url => {168 const frame = document.createElement('iframe');169 frame.name = 'theFrameName';170 frame.src = url;171 document.body.appendChild(frame);172 return new Promise(x => frame.onload = x);173 }, server.EMPTY_PAGE);174 expect(page.frames()[0].name()).toBe('');175 expect(page.frames()[1].name()).toBe('theFrameId');176 expect(page.frames()[2].name()).toBe('theFrameName');177 });178 it('should report frame.parent()', async({page, server}) => {179 await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);180 await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);181 expect(page.frames()[0].parentFrame()).toBe(null);182 expect(page.frames()[1].parentFrame()).toBe(page.mainFrame());183 expect(page.frames()[2].parentFrame()).toBe(page.mainFrame());184 });185 it('should report different frame instance when frame re-attaches', async({page, server}) => {186 const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);187 await page.evaluate(() => {188 window.frame = document.querySelector('#frame1');189 window.frame.remove();190 });191 expect(frame1.isDetached()).toBe(true);192 const [frame2] = await Promise.all([193 utils.waitEvent(page, 'frameattached'),194 page.evaluate(() => document.body.appendChild(window.frame)),195 ]);196 expect(frame2.isDetached()).toBe(false);197 expect(frame1).not.toBe(frame2);198 });199 });200};
frame.js
Source: frame.js
...18})19test.serial('Frame.executionContext should work', async t => {20 const { page, server } = t.context21 await page.goto(server.EMPTY_PAGE)22 await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE)23 t.is(page.frames().length, 2)24 const [frame1, frame2] = page.frames()25 const context1 = await frame1.executionContext()26 const context2 = await frame2.executionContext()27 t.truthy(context1)28 t.truthy(context2)29 t.truthy(context1 !== context2)30 t.is(context1.frame(), frame1)31 t.is(context2.frame(), frame2)32 await Promise.all([33 context1.evaluate(() => (window.a = 1)),34 context2.evaluate(() => (window.a = 2))35 ])36 const [a1, a2] = await Promise.all([37 context1.evaluate(() => window.a),38 context2.evaluate(() => window.a)39 ])40 t.is(a1, 1)41 t.is(a2, 2)42})43test.serial('Frame.evaluateHandle should work', async t => {44 const { page, server } = t.context45 await page.goto(server.EMPTY_PAGE)46 const mainFrame = page.mainFrame()47 const windowHandle = await mainFrame.evaluateHandle(() => window)48 t.truthy(windowHandle)49})50test.serial('Frame.evaluate should throw for detached frames', async t => {51 const { page, server } = t.context52 const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE)53 await utils.detachFrame(page, 'frame1')54 let error = null55 await frame1.evaluate(() => 7 * 8).catch(e => (error = e))56 t.true(57 error.message.includes(58 'Execution Context is not available in detached frame'59 )60 )61})62test.serial('Frame Management should handle nested frames', async t => {63 const { page, server } = t.context64 await page.goto(server.PREFIX + '/frames/nested-frames.html')65 t.deepEqual(utils.dumpFrames(page.mainFrame()), [66 'http://localhost:<PORT>/frames/nested-frames.html',67 ' http://localhost:<PORT>/frames/two-frames.html (2frames)',68 ' http://localhost:<PORT>/frames/frame.html (uno)',69 ' http://localhost:<PORT>/frames/frame.html (dos)',70 ' http://localhost:<PORT>/frames/frame.html (aframe)'71 ])72})73test.serial(74 'Frame Management should send events when frames are manipulated dynamically',75 async t => {76 const { page, server } = t.context77 await page.goto(server.EMPTY_PAGE)78 // validate frameattached events79 const attachedFrames = []80 page.on('frameattached', frame => attachedFrames.push(frame))81 await utils.attachFrame(page, 'frame1', './assets/frame.html')82 t.is(attachedFrames.length, 1)83 t.true(attachedFrames[0].url().includes('/assets/frame.html'))84 // validate framenavigated events85 const navigatedFrames = []86 page.on('framenavigated', frame => navigatedFrames.push(frame))87 await utils.navigateFrame(page, 'frame1', './empty.html')88 t.is(navigatedFrames.length, 1)89 t.is(navigatedFrames[0].url(), server.EMPTY_PAGE)90 // validate framedetached events91 const detachedFrames = []92 page.on('framedetached', frame => detachedFrames.push(frame))93 await utils.detachFrame(page, 'frame1')94 t.is(detachedFrames.length, 1)95 t.true(detachedFrames[0].isDetached())96 }97)98test.serial(99 'Frame Management should send "framenavigated" when navigating on anchor URLs',100 async t => {101 const { page, server } = t.context102 await page.goto(server.EMPTY_PAGE)103 await Promise.all([104 page.goto(server.EMPTY_PAGE + '#foo'),105 utils.waitEvent(page, 'framenavigated')106 ])107 t.is(page.url(), server.EMPTY_PAGE + '#foo')108 }109)110test.serial(111 'Frame Management should persist mainFrame on cross-process navigation',112 async t => {113 const { page, server } = t.context114 await page.goto(server.EMPTY_PAGE)115 const mainFrame = page.mainFrame()116 await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html')117 t.truthy(page.mainFrame() === mainFrame)118 }119)120test.serial(121 'Frame Management should not send attach/detach events for main frame',122 async t => {123 const { page, server } = t.context124 let hasEvents = false125 page.on('frameattached', frame => (hasEvents = true))126 page.on('framedetached', frame => (hasEvents = true))127 await page.goto(server.EMPTY_PAGE)128 t.false(hasEvents)129 }130)131test.serial(132 'Frame Management should detach child frames on navigation',133 async t => {134 const { page, server } = t.context135 let attachedFrames = []136 let detachedFrames = []137 let navigatedFrames = []138 page.on('frameattached', frame => attachedFrames.push(frame))139 page.on('framedetached', frame => detachedFrames.push(frame))140 page.on('framenavigated', frame => navigatedFrames.push(frame))141 await page.goto(server.PREFIX + '/frames/nested-frames.html')142 t.is(attachedFrames.length, 4)143 t.is(detachedFrames.length, 0)144 t.is(navigatedFrames.length, 5)145 attachedFrames = []146 detachedFrames = []147 navigatedFrames = []148 await page.goto(server.EMPTY_PAGE)149 t.is(attachedFrames.length, 0)150 t.is(detachedFrames.length, 4)151 t.is(navigatedFrames.length, 1)152 }153)154test.serial('Frame Management should support framesets', async t => {155 const { page, server } = t.context156 let attachedFrames = []157 let detachedFrames = []158 let navigatedFrames = []159 page.on('frameattached', frame => attachedFrames.push(frame))160 page.on('framedetached', frame => detachedFrames.push(frame))161 page.on('framenavigated', frame => navigatedFrames.push(frame))162 await page.goto(server.PREFIX + '/frames/frameset.html')163 t.is(attachedFrames.length, 4)164 t.is(detachedFrames.length, 0)165 t.is(navigatedFrames.length, 5)166 attachedFrames = []167 detachedFrames = []168 navigatedFrames = []169 await page.goto(server.EMPTY_PAGE)170 t.is(attachedFrames.length, 0)171 t.is(detachedFrames.length, 4)172 t.is(navigatedFrames.length, 1)173})174test.serial(175 'Frame Management should report frame from-inside shadow DOM',176 async t => {177 const { page, server } = t.context178 await page.goto(server.PREFIX + '/shadow.html')179 await page.evaluate(async url => {180 const frame = document.createElement('iframe')181 frame.src = url182 document.body.shadowRoot.appendChild(frame)183 await new Promise(x => (frame.onload = x))184 }, server.EMPTY_PAGE)185 t.is(page.frames().length, 2)186 t.is(page.frames()[1].url(), server.EMPTY_PAGE)187 }188)189test.serial('Frame Management should report frame.name()', async t => {190 const { page, server } = t.context191 await utils.attachFrame(page, 'theFrameId', server.EMPTY_PAGE)192 await page.evaluate(url => {193 const frame = document.createElement('iframe')194 frame.name = 'theFrameName'195 frame.src = url196 document.body.appendChild(frame)197 return new Promise(x => (frame.onload = x))198 }, server.EMPTY_PAGE)199 t.is(page.frames()[0].name(), '')200 t.is(page.frames()[1].name(), 'theFrameId')201 t.is(page.frames()[2].name(), 'theFrameName')202})203test.serial('Frame Management should report frame.parent()', async t => {204 const { page, server } = t.context205 await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE)206 await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE)207 t.falsy(page.frames()[0].parentFrame())208 t.is(page.frames()[1].parentFrame(), page.mainFrame())209 t.is(page.frames()[2].parentFrame(), page.mainFrame())210})211test.serial(212 'Frame Management should report different frame instance when frame re-attaches',213 async t => {214 const { page, server } = t.context215 const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE)216 await page.evaluate(() => {217 window.frame = document.querySelector('#frame1')218 window.frame.remove()219 })220 t.true(frame1.isDetached())221 const [frame2] = await Promise.all([222 utils.waitEvent(page, 'frameattached'),223 page.evaluate(() => document.body.appendChild(window.frame))224 ])225 t.false(frame2.isDetached())226 t.true(frame1 != frame2)227 }...
link.js
Source: link.js
1'use strict';2var EventEmitter = require('events').EventEmitter,3 Promise = require('bluebird'),4 util = require('util'),5 StateMachine = require('stately.js'),6 debug = require('debug')('amqp10:link'),7 u = require('./utilities'),8 pu = require('./policies/policy_utilities'),9 frames = require('./frames'),10 errors = require('./errors');11var stateMachine = function(link) {12 var detachHandler = function(frame) {13 if (this.getMachineState() === 'ATTACHED') {14 this.ATTACHED.sendDetach({ closed: frame.closed });15 }16 link._detached(frame);17 return this.DETACHED;18 };19 var states = {20 'DETACHED': {21 sendAttach: 'ATTACHING',22 reattach: 'REATTACHING'23 },24 'ATTACHING': { attachReceived: 'ATTACHED' },25 'REATTACHING': { attachReceived: 'ATTACHED' },26 'ATTACHED': {27 sendDetach: function(options) {28 link._sendDetach(options);29 return this.DETACHING;30 },31 },32 'DETACHING': { detached: 'DETACHED' }33 };34 Object.keys(states).forEach(function(s) {35 states[s].forceDetach = 'DETACHED';36 states[s].detachReceived = detachHandler;37 });38 return states;39};40/**41 * @class42 * @extends EventEmitter43 * @fires Link#errorReceived44 * @fires Link#attached45 * @fires Link#detached46 */47function Link(session, handle, linkPolicy) {48 this.policy = linkPolicy;49 pu.fixDeprecatedLinkOptions(this.policy);50 this.session = session;51 this.handle = handle;52 this.remote = { handle: undefined };53 this.deliveryCount = 0;54 this._onAttach = [];55 if (this.policy && this.policy.reattach) {56 this._timeouts = u.generateTimeouts(this.policy.reattach);57 }58 var self = this;59 this.sm = new StateMachine(stateMachine(this));60 this.sm.bind(function(event, oldState, newState) {61 debug('stateChange(' + self.id + '):', oldState, '=>', newState, ', reason:', event);62 });63}64util.inherits(Link, EventEmitter);65/**66 * Error received event67 *68 * @event Link#errorReceived69 * @param {object} error the received error70 */71Link.ErrorReceived = 'errorReceived';72/**73 * Attached event74 *75 * @event Link#attached76 */77Link.Attached = 'attached';78/**79 * Detached event80 *81 * @event Link#detached82 */83Link.Detached = 'detached';84// public api85/**86 * Detach the link from the session87 *88 * @inner @memberof Link89 * @param {object} [options] detach frame options90 * @return {Promise}91 */92Link.prototype.detach = function(options) {93 var self = this;94 this._timeouts = undefined; // Disable any re-attachment policy.95 var detachPromise = new Promise(function(resolve, reject) {96 var onError = function(err) { reject(err); };97 self.once(Link.ErrorReceived, onError);98 self.once(Link.Detached, function(info) {99 self.removeListener(Link.ErrorReceived, onError);100 if (!!info.error) return reject(info.error);101 if (!info.closed) {102 if (!options || options.closed) {103 return reject('link not closed');104 }105 }106 resolve();107 });108 });109 this.sm.sendDetach(options);110 return detachPromise;111};112// private api113Link.prototype.state = function() {114 return this.sm.getMachineState().toLowerCase();115};116Object.defineProperty(Link.prototype, 'id', {117 get: function() { return this.name + ':' + this.handle; }118});119Link.prototype.attach = function() {120 this.sm.sendAttach();121 var attachFrame = new frames.AttachFrame(this.policy.attach);122 attachFrame.channel = this.session.channel;123 this.name = attachFrame.name;124 this.role = attachFrame.role;125 this.linkCredit = 0;126 this.available = 0;127 this.drain = false;128 this.session.connection.sendFrame(attachFrame);129};130///131/// Force link state to detached without sending detach message - usually due to forcible disconnect or unmap from above.132/// Important bit is that this should not trigger auto-reattach behavior as that'll happen with reconnect.133///134Link.prototype.forceDetach = function() {135 var state = this.state();136 if (state !== 'attached' && state !== 'attaching' && state !== 'reattaching') {137 return;138 }139 debug('forceDetach(' + this.id + '): current state:', state);140 if (!!this._reattachTimer) clearTimeout(this._reattachTimer);141 this.sm.forceDetach();142 this.emit(Link.Detached, {143 closed: true,144 error: new errors.ProtocolError('amqp:link:detach-forced', 'detach-forced')145 });146};147Link.prototype._resolveAttachPromises = function(err, link) {148 for (var i = 0; i < this._onAttach.length; ++i) {149 var attachPromise = this._onAttach[i];150 attachPromise(err, link);151 }152 this._onAttach = [];153};154Link.prototype._attachReceived = function(attachFrame) {155 this.sm.attachReceived();156 // process params.157 this.remote.handle = attachFrame.handle;158 this.remote.attach = attachFrame;159 this.session._linksByRemoteHandle[this.remote.handle] = this;160 debug(this.name + ': attached CH=[' + this.session.channel + '=>' + attachFrame.channel + '], Handle=[' + this.handle + '=>' + attachFrame.handle + ']');161 this.emit(Link.Attached, this);162 this._resolveAttachPromises(null, this);163 this._checkCredit({ initial: true });164};165// default implementation does nothing166Link.prototype._checkCredit = function() {};167Link.prototype.flow = function(options) {168 options = options || {};169 var flowOptions = u.defaults(options, {170 channel: this.session.channel,171 handle: this.handle,172 linkCredit: this.linkCredit,173 nextIncomingId: this.session._sessionParams.nextIncomingId,174 incomingWindow: this.session._sessionParams.incomingWindow,175 nextOutgoingId: this.session._sessionParams.nextOutgoingId,176 outgoingWindow: this.session._sessionParams.outgoingWindow,177 available: this.available,178 deliveryCount: this.deliveryCount,179 drain: false180 });181 this.session.connection.sendFrame(new frames.FlowFrame(flowOptions));182};183Link.prototype._sendDetach = function(options) {184 options = options || {};185 var detachoptions = u.defaults(options, {186 handle: this.handle,187 channel: this.session.channel,188 closed: true,189 error: null190 });191 this.session.connection.sendFrame(new frames.DetachFrame(detachoptions));192};193Link.prototype._detached = function(frame) {194 if (frame && frame.error) {195 this.emit(Link.ErrorReceived, errors.wrapProtocolError(frame.error));196 }197 this.remote.detach = frame;198 if (this.remote.handle !== undefined) {199 delete this.session._linksByRemoteHandle[this.remote.handle];200 this.remote.handle = undefined;201 }202 this.emit(Link.Detached, { closed: frame.closed, error: errors.wrapProtocolError(frame.error) });203 this._resolveAttachPromises(frame.error ? frame.error : 'link closed');204 this.sm.detached();205 // now check for whether we should reattach206 var self = this;207 if (self.shouldReattach()) {208 process.nextTick(function() { self._attemptReattach(); });209 }210};211Link.prototype.shouldReattach = function() {212 if (this.session && !this.session.mapped) return false;213 if (!this.session || !this._timeouts) return false;214 if (!this._timeouts.length && !this.policy.reattach.forever) return false;215 return true;216};217Link.prototype._attemptReattach = function() {218 var self = this;219 if (!self._timeouts.length) {220 self._timeouts = u.generateTimeouts(self.policy.reattach);221 }222 self.sm.reattach();223 self._reattachTimer = setTimeout(function() {224 if (self.shouldReattach()) {225 debug('attempting to reattach: ' + self.id);226 self.attach();227 } else {228 process.nextTick(function() { self._attemptReattach(); });229 }230 }, self._timeouts.shift());231};...
rte.util.js
Source: rte.util.js
1jQuery(document).ready(function () {2 var comment = document.getElementById("respond");3 var replyrow = document.getElementById("replyrow");4 if (comment && typeof (comment) != "undefined")5 {6 window.RTECONTAINER = comment;7 window.RTECHECKERTIMER = setInterval(RTE_CheckParent, 100);8 }9 else if (replyrow && typeof (replyrow) != "undefined")10 {11 window.RTECONTAINER = replyrow;12 window.RTECHECKERTIMER = setInterval(RTE_CheckParent, 100);13 } 14});15function RTE_CheckParent()16{17 /*for 3.0-3.2*/18 var ed_reply_qtags = document.getElementById("ed_reply_qtags");19 if (ed_reply_qtags && typeof (ed_reply_qtags) != "undefined")20 ed_reply_qtags.style.display="none";21 var post_status_info = document.getElementById("post-status-info");22 if (post_status_info && typeof (post_status_info) != "undefined")23 post_status_info.style.display = "none";24 var editor_toolbar = document.getElementById("editor-toolbar");25 if (editor_toolbar && typeof (editor_toolbar) != "undefined")26 editor_toolbar.style.display = "none";27 var quicktags = document.getElementById("quicktags");28 if (quicktags && typeof (quicktags) != "undefined")29 quicktags.style.display = "none";30 var content_parent = document.getElementById("content_parent");31 if (content_parent && typeof (content_parent) != "undefined")32 content_parent.style.display = "none";33 var editorcontainer = document.getElementById("editorcontainer");34 if (editorcontainer && typeof (editorcontainer) != "undefined")35 editorcontainer.style.border = "none";36 /*check reply row*/37 var replyrow = document.getElementById("replyrow");38 if (replyrow && !document.getElementById("content"))39 {40 var prow = replyrow.parentNode;41 var trs = prow.getElementsByTagName("tr");42 var ci = -1;43 for (var i = 0; i < trs.length; i++)44 {45 if (!trs[i].id)46 continue;47 if (trs[i].id == replyrow.id)48 {49 ci = i;50 break;51 }52 }53 if (ci == -1)54 return;55 if (!window.WP_REPLYROWINDEX) {56 window.WP_REPLYROWINDEX = ci;57 window.WP_RTEEDITOR.DetachFrame();58 window.WP_RTEEDITOR.AttachFrame();59 window.WP_RTEEDITOR.SetText("");60 return;61 }62 if (ci != window.WP_REPLYROWINDEX)63 {64 window.WP_REPLYROWINDEX = ci;65 window.WP_RTEEDITOR.DetachFrame();66 window.WP_RTEEDITOR.AttachFrame();67 window.WP_RTEEDITOR.SetText("");68 }69 return;70 }71 /*end for 3.0-3.2*/72 if (!window.WP_RTEEDITOR)73 return;74 if (!window.RTECONTAINER)75 return;76 if (!window.RTEPARENT)77 {78 window.RTEPARENT = window.RTECONTAINER.parentNode;79 return;80 }81 var curparent = window.RTECONTAINER.parentNode;82 //document.title = [curparent, window.RTEPARENT];83 if (window.RTEPARENT == curparent)84 return;85 window.RTEPARENT = curparent;86 window.WP_RTEEDITOR.DetachFrame();87 //rteeditor._config.skin_div_parent.insertBefore(div, rteeditor._config.skin_div_holder);88 //rteeditor._config.skin_div_parent.removeChild(rteeditor._config.skin_div_holder);89 //rteeditor._config.skin_div_holder = div;90 window.WP_RTEEDITOR.AttachFrame();91 window.WP_RTEEDITOR.SetText("");...
TaskExecutor.js
Source: TaskExecutor.js
1// @flow2import * as React from 'react';3type ExecutorMessage = {4 command: string,5 payload: any,6};7export type CommandHandler = (payload: any) => void | Promise<void>;8type Props = {|9 code: string,10 handlers: {11 [command: string]: CommandHandler,12 },13|};14type Instance = React.ElementRef<'iframe'>;15const fetchExecutorDoc = fetch('/executor').then((response) => response.text());16/**17 * A TaskExecutor encapsulates a single hidden, sandboxed iframe containing the `/executor` document.18 * TaskExecutors are managed by an executor.19 *20 * The component sets up communication facilities for communication between the iframe and the IDE.21 */22const TaskExecutor = React.forwardRef<Props, Instance>(23 ({ code, handlers }: Props, ref: Ref<Instance>) => {24 // load the executorDoc in the beginning25 const [executorDoc, setExecutorDoc] = React.useState<string | null>(null);26 React.useEffect(() => {27 fetchExecutorDoc.then(setExecutorDoc);28 }, []);29 // the frame, stored for local use30 const [frame, setFrame] = React.useState<React.ElementRef<'iframe'> | null>(null);31 // uses useCallback because otherwise each render resets the ref.32 // (the ref could be registered with a new callback, so the callback needs to be stable)33 const attachFrame = React.useCallback(34 (f) => {35 // set the ref for this component36 if (typeof ref === 'function') ref(f);37 else ref.current = f;38 // set the frame state variable39 setFrame(f);40 },41 [ref],42 );43 // register message listener44 React.useEffect(() => {45 if (frame === null) return undefined;46 function receiveMessage({ data, origin, source }: MessageEvent) {47 if (origin !== 'null' || source !== frame.contentWindow) return;48 const { command, payload } =49 // if the source is what we expected, we assume the data is valid50 // $FlowExpectError51 (data: ExecutorMessage);52 handlers[command]?.(payload);53 }54 window.addEventListener('message', receiveMessage, false);55 return () => {56 window.removeEventListener('message', receiveMessage);57 };58 }, [frame, handlers]);59 // send execute command to iframe60 React.useEffect(() => {61 if (frame === null) return;62 frame.onload = () => {63 const sender = null;64 const command = 'init';65 const payload = code;66 frame.contentWindow.postMessage({ sender, command, payload }, '*');67 };68 }, [frame, code]);69 // only render the iframe after loading the executorDoc70 if (executorDoc === null) return null;71 return (72 // eslint-disable-next-line jsx-a11y/iframe-has-title73 <iframe74 ref={attachFrame}75 sandbox="allow-scripts"76 // src="/executor"77 srcDoc={executorDoc}78 style={{ display: 'none' }}79 />80 );81 },82);...
utils.js
Source: utils.js
...20 * @param {string} url21 */22 attachFrame: async function(page, frameId, url) {23 await page.evaluate(attachFrame, frameId, url);24 function attachFrame(frameId, url) {25 const frame = document.createElement('iframe');26 frame.src = url;27 frame.id = frameId;28 document.body.appendChild(frame);29 return new Promise(x => frame.onload = x);30 }31 },32 /**33 * @param {!Page} page34 * @param {string} frameId35 */36 detachFrame: async function(page, frameId) {37 await page.evaluate(detachFrame, frameId);38 function detachFrame(frameId) {...
frame-utils.js
Source: frame-utils.js
...21 * @return {!Promise}22 */23 attachFrame: async function(page, frameId, url) {24 await page.evaluate(attachFrame, frameId, url);25 function attachFrame(frameId, url) {26 const frame = document.createElement('iframe');27 frame.src = url;28 frame.id = frameId;29 document.body.appendChild(frame);30 return new Promise(x => frame.onload = x);31 }32 },33 /**34 * @param {!Page} page35 * @param {string} frameId36 * @return {!Promise}37 */38 detachFrame: async function(page, frameId) {39 await page.evaluate(detachFrame, frameId);...
Using AI Code Generation
1const { attachFrame } = require('playwright/lib/server/chromium/crPage');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const frame = await page.frames()[0];7 await attachFrame(page, frame._id, frame._url);8 await page.evaluate((id) => {9 const frame = document.getElementById(id);10 frame.remove();11 }, frame._id);12 await browser.close();13})();14import { chromium } from 'playwright';15const { chromium } = require('playwright');16import { chromium } from 'playwright';17const { chromium } = require('playwright');18import { chromium } from 'playwright';19(async () => {20 const browser = await chromium.launch();21 const page = await browser.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25import { chromium } from 'playwright';26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();
Using AI Code Generation
1const { attachFrame } = 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 console.log(frame.url());8 await browser.close();9})();
Using AI Code Generation
1const { attachFrame } = require('playwright/lib/server/chromium/crPage');2const path = require('path');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const frame = await attachFrame(page, null, path.join(__dirname, 'frame.html'));7 await frame.waitForSelector('h1');8 await browser.close();9})();10The attachFrame method takes three parameters: the page object, the name of the frame (null in this case) and the path to the file
Using AI Code Generation
1const { attachFrame } = require('@playwright/test/lib/frame');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 frame.click('text=About');8 await page.close();9 await context.close();10 await browser.close();11})();12const { attachFrame } = require('@playwright/test/lib/frame');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 frame.click('text=About');19 await page.close();20 await context.close();21 await browser.close();22})();23const { attachFrame } = require('@playwright/test/lib/frame');24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch();27 const context = await browser.newContext();28 const page = await context.newPage();29 await frame.click('text=About');30 await page.close();31 await context.close();32 await browser.close();33})();34const { attachFrame } = require('@playwright/test/lib/frame');35const { chromium } = require('playwright');36(async () => {37 const browser = await chromium.launch();38 const context = await browser.newContext();39 const page = await context.newPage();40 await frame.click('text=About');41 await page.close();42 await context.close();
Using AI Code Generation
1const { chromium } = require('playwright-chromium');2const { attachFrame } = require('playwright-core/lib/server/chromium/crPage');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const frames = await page.frames();8 const frame = frames[1];9 const element = await frame.$('#hplogo');10 await attachFrame(page, frame, element);11 await browser.close();12})();
Using AI Code Generation
1const { attachFrame } = require('playwright-core/lib/server/chromium/crPage');2const { createTestServer } = require('playwright-core/lib/utils/testserver/');3const { chromium } = require('playwright-core');4(async () => {5 const server = await createTestServer();6 server.setRoute('/empty.html', (req, res) => {7 res.end();8 });9 server.setRoute('/frame.html', (req, res) => {10 res.end(`11 <iframe src="${server.PREFIX}/empty.html"></iframe>12 `);13 });14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.goto(server.EMPTY_PAGE);18 await page.setContent(`<iframe src="${server.PREFIX}/frame.html"></iframe>`);19 const frame = page.frames()[1];20 const childFrame = frame.childFrames()[0];21 await attachFrame(page, 'frameId', server.EMPTY_PAGE);22 await page.evaluate(frameId => {23 window.frames[frameId].location.href = '/empty.html';24 }, 'frameId');25 await childFrame.waitForNavigation();26 await browser.close();27 await server.stop();28})();29module.exports = {30 use: {31 }32};33{34 "scripts": {35 },36 "dependencies": {37 }38}
Using AI Code Generation
1const { attachFrame } = require('playwright/lib/server/chromium/crPage');2const { chromium } = require('playwright');3const { createServer } = require('http-server');4(async () => {5 const server = createServer({ root: '.' });6 server.listen(8080);7 const browser = await chromium.launch({ headless: false });8 const page = await browser.newPage();9 await frame.waitForSelector('text=Playwright');10 await frame.click('text=Playwright');11 await browser.close();12 server.close();13})();14<button onclick="window.alert('Hello')">Click me</button>
Using AI Code Generation
1const { chromium, webkit, firefox } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const frame = page.mainFrame().childFrames()[0];7 await page.evaluate(() => {8 window.attachFrame = (frame) => {9 document.body.appendChild(frame);10 };11 });12 await page.evaluate(frame => window.attachFrame(frame), frame);13 await page.screenshot({ path: 'test.png' });14 await browser.close();15})();16const { test, expect } = require('@playwright/test');17test('test', async ({ page }) => {18 await page.goto('test.html');19 const frame = page.mainFrame().childFrames()[0];20 await page.evaluate(() => {21 window.attachFrame = (frame) => {22 document.body.appendChild(frame);23 };24 });25 await page.evaluate(frame => window.attachFrame(frame), frame);26 await page.screenshot({ path: 'test.png' });27});
Using AI Code Generation
1const { attachFrame } = require('playwright-core/lib/server/dom.js');2const frame = await attachFrame(page, 'frameId', 'frameName', 'frameUrl');3const { detachFrame } = require('playwright-core/lib/server/dom.js');4await detachFrame(page, frame);5const { attachWorker } = require('playwright-core/lib/server/dom.js');6const worker = await attachWorker(page, 'workerId', 'workerUrl');7const { detachWorker } = require('playwright-core/lib/server/dom.js');8await detachWorker(page, worker);9const { setFileChooserIntercepted } = require('playwright-core/lib/server/dom.js');10await setFileChooserIntercepted(page, true);11const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');12await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);13const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');14await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);15const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');16await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);17const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');18await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);19const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');20await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);21const { setFileChooserFiles } = require('playwright-core/lib/server/dom.js');22await setFileChooserFiles(page, ['path/to/file1', 'path/to/file2']);
How to run a list of test suites in a single file concurrently in jest?
Is it possible to get the selector from a locator object in playwright?
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Running Playwright in Azure Function
firefox browser does not start in playwright
Assuming you are not running test with the --runinband
flag, the simple answer is yes but it depends ????
There is a pretty comprehensive GitHub issue jest#6957 that explains certain cases of when tests are run concurrently or in parallel. But it seems to depend on a lot of edge cases where jest tries its best to determine the fastest way to run the tests given the circumstances.
To my knowledge there is no way to force jest to run in parallel.
Have you considered using playwright
instead of puppeteer with jest? Playwright has their own internally built testing library called @playwright/test
that is used in place of jest with a similar API. This library allows for explicitly defining test groups in a single file to run in parallel (i.e. test.describe.parallel
) or serially (i.e. test.describe.serial
). Or even to run all tests in parallel via a config option.
// parallel
test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {});
test('runs in parallel 2', async ({ page }) => {});
});
// serial
test.describe.serial('group', () => {
test('runs first', async ({ page }) => {});
test('runs second', async ({ page }) => {});
});
Check out the latest blogs from LambdaTest on this topic:
Automating testing is a crucial step in the development pipeline of a software product. In an agile development environment, where there is continuous development, deployment, and maintenance of software products, automation testing ensures that the end software products delivered are error-free.
These days, development teams depend heavily on feedback from automated tests to evaluate the quality of the system they are working on.
In recent times, many web applications have been ported to mobile platforms, and mobile applications are also created to support businesses. However, Android and iOS are the major platforms because many people use smartphones compared to desktops for accessing web applications.
Software testing is fueling the IT sector forward by scaling up the test process and continuous product delivery. Currently, this profession is in huge demand, as it needs certified testers with expertise in automation testing. When it comes to outsourcing software testing jobs, whether it’s an IT company or an individual customer, they all look for accredited professionals. That’s why having an software testing certification has become the need of the hour for the folks interested in the test automation field. A well-known certificate issued by an authorized institute kind vouches that the certificate holder is skilled in a specific technology.
JavaScript is one of the most widely used programming languages. This popularity invites a lot of JavaScript development and testing frameworks to ease the process of working with it. As a result, numerous JavaScript testing frameworks can be used to perform unit testing.
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!!