Best JavaScript code snippet using playwright-internal
browserContext.js
Source:browserContext.js
...323 await this._wrapApiCall(async () => {324 var _this$_browserType2, _this$_browserType2$_;325 await ((_this$_browserType2 = this._browserType) === null || _this$_browserType2 === void 0 ? void 0 : (_this$_browserType2$_ = _this$_browserType2._onWillCloseContext) === null || _this$_browserType2$_ === void 0 ? void 0 : _this$_browserType2$_.call(_this$_browserType2, this));326 if (this._options.recordHar) {327 const har = await this._channel.harExport();328 const artifact = _artifact.Artifact.from(har.artifact);329 await artifact.saveAs(this._options.recordHar.path);330 await artifact.delete();331 }332 }, true);333 await this._channel.close();334 await this._closedPromise;335 } catch (e) {336 if ((0, _errors.isSafeCloseError)(e)) return;337 throw e;338 }339 }340 async _enableRecorder(params) {341 await this._channel.recorderSupplementEnable(params);...
bookmark.js
Source:bookmark.js
1/*2 Copyright (C) 2017-present Mirko Perillo and contributors3 4 This file is part of Resting.5 Resting is free software: you can redistribute it and/or modify6 it under the terms of the GNU General Public License as published by7 the Free Software Foundation, either version 3 of the License, or8 (at your option) any later version.9 Resting is distributed in the hope that it will be useful,10 but WITHOUT ANY WARRANTY; without even the implied warranty of11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 GNU General Public License for more details.13 You should have received a copy of the GNU General Public License14 along with Resting. If not, see <http://www.gnu.org/licenses/>.15 */16 17define(function() {18 const makeBookmarkFromJson = ({id, request, name, folder, created}) => ({ id, request, name, folder, isFolder: false, created});19 const makeFolderFromJson= ({id,name,bookmarks = [], created}) => ({id,name, bookmarks, isFolder : true, created});20 const makeBookmark = (id, request, name, folder, created = new Date()) => ({ id, request, name, folder, isFolder: false, created});21 const makeFolder= (id,name,bookmarks = [], created = new Date()) => ({id,name, bookmarks, isFolder : true, created});22 const fromJson = (json = {}) => {23 const obj = JSON.parse(json);24 if(obj.isFolder) {25 return makeFolderFromJson(obj);26 } else {27 return makeBookmarkFromJson(obj);28 }29 };30 const addBookmarks = (folder,bookmarks = []) => {31 const newFolder = Object.assign({},folder);32 newFolder.bookmarks = folder.bookmarks.concat(bookmarks);33 return newFolder;34 }35 const bookmarkById = ({ id }) => b => (b.id === id);36 const sortBookmarks = (folder, criteria) => {37 const bookmarks = folder.bookmarks38 bookmarks.sort(criteria)39 return Object.assign({}, folder, {bookmarks})40 }41 const replaceBookmark = (folder,bookmark) => {42 const bookmarks = folder.bookmarks.slice();43 const indexToReplace = bookmarks.findIndex(bookmarkById(bookmark));44 if(indexToReplace !== -1) {45 bookmarks.splice(indexToReplace,1, bookmark);46 } else {47 bookmarks.push(bookmark);48 }49 return Object.assign({}, folder, {bookmarks});50 };51 const removeBookmarks = (folder,bookmarksToRemove = []) => {52 let bookmarks = folder.bookmarks.slice();53 const bookmarksToRemoveIds = (Array.isArray(bookmarksToRemove)54 ? bookmarksToRemove55 : [bookmarksToRemove])56 .map(b => b.id);57 bookmarks = bookmarks.filter(b => bookmarksToRemoveIds.indexOf(b.id) === -1);58 return Object.assign({},folder,{bookmarks});59 };60 const copyBookmark = (bookmark) => {61 return Object.assign({},bookmark);62 };63 const importHAR = (storageProvider, harContent) => (harContent) => {64 const har = JSON.parse(_escapeJsonContent(harContent));65 if(_isRestingFormat(har.log.creator)) {66 return importObj(har);67 } else {68 const harEntries = har.log.entries;69 const bookmarks = harEntries.map(entry => _convertHarEntry(storageProvider, entry));70 return {bookmarks : bookmarks, contexts : []};71 }72 // return bookmarks;73 };74 const _isRestingFormat = (creatorFields = {}) => {75 return creatorFields.name == 'Resting WebExtension' && creatorFields.version == '1.0';76 };77 const _escapeJsonContent = (content) => {78 /*if(content) {79 content = content.replace(/\n/g,'');80 content = content.replace(/\t/g,'');81 content = content.replace(/\r/g,'');82 content = content.replace(/"response":\s?{.*},"/,'"response": {},"');83 }84 return content;*/85 return content.replace(/\\n/g, "\\n")86 .replace(/\\'/g, "\\'")87 .replace(/\\"/g, '\\"')88 .replace(/\\&/g, "\\&")89 .replace(/\\r/g, "\\r")90 .replace(/\\t/g, "\\t")91 .replace(/\\b/g, "\\b")92 .replace(/\\f/g, "\\f");93 };94 const _convertHarEntry = (storage, entry) => {95 const bookmark = {};96 bookmark.id = storage.generateId();97 bookmark.name = entry.pageref;98 bookmark.request = _convertHarRequest(entry.request);99 return bookmark;100 };101 const _convertHarRequest = (harRequest = {}) => {102 const request = {};103 if(harRequest.url) {104 const querystringIndex = harRequest.url.indexOf('?');105 const endUrlIndex = querystringIndex != -1 ? querystringIndex : harRequest.url.length;106 request.url = harRequest.url.substring(0, endUrlIndex);107 }108 request.method = harRequest.method;109 if(harRequest.queryString) {110 request.querystring = harRequest.queryString.map((qs) => ({name: qs.name, value: qs.value}));111 }112 if(harRequest.headers) {113 request.headers = harRequest.headers.map(header => ({name: header.name, value: header.value}));114 }115 if(harRequest.postData) {116 request.headers.push({name:'Content-Type', value: harRequest.postData.mimeType});117 request.body = harRequest.postData.text;118 }119 return request;120 };121 const exportObj = (bookmarks = [], contexts = []) => {122 let harExport = {};123 harExport.log = {};124 harExport.log.version = '1.1';125 harExport.log.creator = {};126 harExport.log.creator.name = 'Resting WebExtension';127 harExport.log.creator.version = '1.0';128 harExport.log.entries = _bookmarkToHar(bookmarks);129 harExport.log._contexts = _contextsToHar(contexts);130 return harExport;131 };132 const _contextsToHar = (contexts = []) => {133 return contexts.map(c => {134 let contextHarField = {};135 contextHarField.name = c.name;136 contextHarField.variables = c.variables.map(v => ({name: v.name, value: v.value, enabled: v.enabled}));137 return contextHarField;138 }139 );140 };141 const _bookmarkToHar = (sources = []) => {142 let exported = [];143 if(sources.length > 0) {144 let bookmarkExport = {};145 bookmarkExport._name = sources[0].name;146 bookmarkExport._isFolder = sources[0].isFolder;147 bookmarkExport._id = sources[0].id;148 bookmarkExport._created = sources[0].created;149 bookmarkExport._folder = sources[0].folder;150 bookmarkExport.startedDateTime = "1970-01-01T00:00:00Z"; // not supported151 bookmarkExport.request = {headersSize: -1, bodySize: -1, httpVersion:'', cookies: [], url: '', method: '', headers: [], queryString: []};152 bookmarkExport.response = {status: 0, statusText: '', httpVersion:'', cookies:[], headers: [], redirectURL:'', headersSize: -1, bodySize: -1, content: {size: 0, mimeType: ''}};153 bookmarkExport.cache = {};154 bookmarkExport.timings = {wait: -1, send: -1, receive: -1};155 bookmarkExport.time = -1;156 if(sources[0].request) {157 if(sources[0].request.url) {158 bookmarkExport.request.url = sources[0].request.url;159 } else {160 bookmarkExport.request.url = '';161 }162 if(sources[0].request.method) {163 bookmarkExport.request.method = sources[0].request.method;164 } else {165 bookmarkExport.request.method = '';166 }167 if(sources[0].request.headers) {168 bookmarkExport.request.headers = sources[0].request.headers.map(h => ({name: h.name, value: h.value, _enabled: h.enabled}));169 } else {170 bookmarkExport.request.headers = [];171 }172 if(sources[0].request.querystring) {173 bookmarkExport.request.queryString = sources[0].request.querystring.map(q => ({name: q.name, value: q.value, _enabled: q.enabled}));174 } else {175 bookmarkExport.request.queryString = [];176 }177 if(sources[0].request.body) {178 bookmarkExport.request.postData = {};179 bookmarkExport.request.postData.mimeType = _getMimeType(sources[0].request.bodyType);180 if(bookmarkExport.request.postData.mimeType === 'application/x-www-form-urlencoded' || bookmarkExport.request.postData.mimeType === 'multipart/form-data') {181 bookmarkExport.request.postData.params = sources[0].request.body.map(p => ({name: p.name, value: p.value, _enabled: p.enabled}));;182 } else {183 bookmarkExport.request.postData.text = sources[0].request.body;184 }185 }186 bookmarkExport.request._authentication = sources[0].request.authentication;187 bookmarkExport.request._context = sources[0].request.context;188 }189 exported.push(bookmarkExport);190 if(bookmarkExport._isFolder) {191 exported = exported.concat(_bookmarkToHar(sources[0].bookmarks));192 }193 exported = exported.concat(_bookmarkToHar(sources.slice(1)));194 }195 return exported;196 };197 const _getMimeType = repr => {198 switch(repr){199 case 'form-data':200 return 'multipart/form-data';201 case 'raw':202 return 'application/json';203 default:204 case 'x-www-form-urlencoded':205 return 'application/x-www-form-urlencoded';206 }207 };208 const _getBodyType = mime => {209 switch(mime){210 case 'multipart/form-data':211 return 'form-data';212 case 'application/json':213 return 'raw';214 default:215 case 'application/x-www-form-urlencoded':216 return 'x-www-form-urlencoded';217 }218 };219 const importObj = (obj = {}) => {220 let importObj = {};221 const entries = obj.log ? obj.log.entries : undefined;222 const contexts = obj.log ? obj.log._contexts : undefined;223 if(entries) {224 const indexRelationship = _extractRelationship(entries);225 importObj.bookmarks = entries.map(e => _importEntry(e));226 importObj.bookmarks = _fixStructure(importObj.bookmarks, indexRelationship);227 }228 if(contexts) {229 importObj.contexts = contexts.map(e => _importContext(e));230 }231 return importObj;232 };233 const _fixStructure = (bookmarks, mapping) => {234 let indexBookmarks = {};235 let i = 0;236 let bookmark;237 for(bookmark of bookmarks) {238 const bookmarkId = bookmark.id;239 indexBookmarks[bookmarkId] = {obj: bookmark, position: i};240 i++;241 }242 let folderId;243 for( folderId of Object.keys(mapping) ) {244 const insideBookmarkIds = mapping[folderId];245 insideBookmarkIds.forEach(id => {246 if(!indexBookmarks[folderId].obj.bookmarks) {247 indexBookmarks[folderId].obj.bookmarks = [];248 }249 indexBookmarks[folderId].obj.bookmarks.push(indexBookmarks[id].obj);250 bookmarks.splice(indexBookmarks[id].position,1);251 });252 }253 return bookmarks;254 }255 const _extractRelationship = (entries = []) => {256 let relationMapping = {};257 entries.forEach((e) => {258 const id = e._id;259 const folderId = e._folder;260 if(folderId) {261 if(!relationMapping.folderId) {262 relationMapping[folderId] = [];263 }264 relationMapping[folderId].push(id);265 }266 });267 return relationMapping;268 };269 const _importEntry = (entry = {}) => {270 let bookmark = {};271 bookmark.request = {};272 bookmark.isFolder = entry._isFolder;273 bookmark.folder = entry._folder;274 if(entry._name) {275 bookmark.name = entry._name;276 }277 if(entry._id) {278 bookmark.id = entry._id;279 }280 if(entry._created) {281 bookmark.created = entry._created;282 }283 const entryRequest = entry.request;284 bookmark.request.context = entryRequest._context;285 if(entryRequest.url) {286 bookmark.request.url = entryRequest.url;287 }288 if(entryRequest.method) {289 bookmark.request.method = entryRequest.method;290 }291 if(entryRequest.headers) {292 bookmark.request.headers = entryRequest.headers.map(h => ({name: h.name, value: h.value, enabled: h._enabled}));293 }294 if(entryRequest.queryString) {295 bookmark.request.querystring = entryRequest.queryString.map(h => ({name: h.name, value: h.value, enabled: h._enabled}));296 }297 if(entryRequest._authentication) {298 bookmark.request.authentication = entryRequest._authentication;299 }300 if(entryRequest.postData) {301 bookmark.request.bodyType = _getBodyType(entryRequest.postData.mimeType);302 if(entryRequest.postData.mimeType === 'multipart/form-data' || entryRequest.postData.mimeType === 'application/x-www-form-urlencoded') {303 bookmark.request.body = entryRequest.postData.params.map(p => ({name: p.name, value: p.value, enabled: p._enabled}));304 } else {305 bookmark.request.body = entryRequest.postData.text;306 }307 }308 return bookmark;309 };310 const _importContext = (entry = {}) => {311 let context = {};312 if(entry.name) {313 context.name = entry.name;314 }315 if(entry.variables) {316 context.variables = entry.variables.map(v => ({name: v.name, value: v.value, enabled: v.enabled}));317 }318 return context;319 };320 return function(storageProvider) {321 return {322 makeBookmark : makeBookmark,323 makeFolder : makeFolder,324 fromJson : fromJson,325 addBookmarks : addBookmarks,326 removeBookmarks : removeBookmarks,327 copyBookmark : copyBookmark,328 replaceBookmark : replaceBookmark,329 sortBookmarks,330 save : bookmark => storageProvider.save(bookmark),331 importHAR : importHAR(storageProvider),332 exportObj,333 importObj,334 };335 };...
har.test.js
Source:har.test.js
1import path from 'path';2import * as harUtils from '../har';3import * as render from '../render';4import * as models from '../../models';5import { AUTH_BASIC } from '../constants';6import { globalBeforeEach } from '../../__jest__/before-each';7describe('exportHar()', () => {8 beforeEach(globalBeforeEach);9 it('exports single requests', async () => {10 const wrk = await models.workspace.create({11 _id: 'wrk_1',12 name: 'Workspace'13 });14 const req1 = await models.request.create({15 _id: 'req_1',16 name: 'Request 1',17 parentId: wrk._id,18 url: 'https://httpstat.us/200',19 method: 'POST',20 body: {21 mimeType: 'application/json',22 text: '{}'23 },24 headers: [25 { name: 'Content-Type', value: 'application/json' },26 { name: 'Accept', value: 'application/json', disabled: false },27 { name: 'X-Disabled', value: 'X-Disabled', disabled: true }28 ]29 });30 await models.response.create({31 parentId: req1._id,32 statusCode: 200,33 statusMessage: 'OK',34 elapsedTime: 999,35 headers: [{ name: 'Content-Type', value: 'application/json' }],36 contentType: 'application/json',37 bodyPath: path.join(__dirname, '../__fixtures__/har/test-response.json'),38 bodyCompression: null39 });40 const exportRequests = [{ requestId: req1._id, environmentId: 'n/a' }];41 const harExport = await harUtils.exportHar(exportRequests);42 expect(harExport).toMatchObject({43 log: {44 version: '1.2',45 creator: {46 name: 'Insomnia REST Client'47 },48 entries: [49 {50 startedDateTime: expect.any(String),51 time: 999,52 request: {53 method: 'POST',54 url: 'https://httpstat.us/200',55 httpVersion: 'HTTP/1.1',56 cookies: [],57 headers: [58 { name: 'Content-Type', value: 'application/json' },59 { name: 'Accept', value: 'application/json' }60 ],61 queryString: [],62 postData: {63 mimeType: 'application/json',64 params: [],65 text: '{}'66 },67 headersSize: -1,68 bodySize: -169 },70 response: {71 status: 200,72 statusText: 'OK',73 httpVersion: 'HTTP/1.1',74 cookies: [],75 headers: [{ name: 'Content-Type', value: 'application/json' }],76 content: {77 size: 15,78 mimeType: 'application/json',79 text: '{"key":"value"}'80 },81 redirectURL: '',82 headersSize: -1,83 bodySize: -184 },85 cache: {},86 timings: {87 blocked: -1,88 dns: -1,89 connect: -1,90 send: 0,91 wait: 999,92 receive: 0,93 ssl: -194 },95 comment: req1.name96 }97 ]98 }99 });100 });101 it('exports multiple requests', async () => {102 const workspace = await models.workspace.create({103 _id: 'wrk_1',104 name: 'Workspace'105 });106 const baseReq = await models.request.create({107 _id: 'req_0',108 type: models.request.type,109 name: 'Request',110 parentId: workspace._id,111 url: 'http://localhost',112 method: 'GET',113 body: {},114 headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }]115 });116 const req1 = await models.request.duplicate(baseReq);117 req1._id = 'req_1';118 req1.name = 'Request 1';119 req1.headers.push({ name: 'X-Request', value: '1' });120 await models.request.create(req1);121 const req2 = await models.request.duplicate(baseReq);122 req2._id = 'req_2';123 req2.name = 'Request 2';124 req2.headers.push({ name: 'X-Request', value: '2' });125 await models.request.create(req2);126 const req3 = await models.request.duplicate(baseReq);127 req3._id = 'req_3';128 req3.name = 'Request 3';129 req3.headers.push({ name: 'X-Request', value: '3' });130 await models.request.create(req3);131 await models.response.create({132 _id: 'res_1',133 parentId: req1._id,134 statusCode: 204135 });136 await models.response.create({137 _id: 'res_2',138 parentId: req2._id,139 statusCode: 404140 });141 await models.response.create({142 _id: 'res_3',143 parentId: req3._id,144 statusCode: 500145 });146 const envBase = await models.environment.getOrCreateForWorkspace(workspace);147 await models.environment.update(envBase, {148 data: {149 envvalue: ''150 }151 });152 const envPublic = await models.environment.create({153 _id: 'env_1',154 name: 'Public',155 parentId: envBase._id156 });157 await models.environment.update(envPublic, {158 data: {159 envvalue: 'public'160 }161 });162 const envPrivate = await models.environment.create({163 _id: 'env_2',164 name: 'Private',165 isPrivate: true,166 parentId: envBase._id167 });168 await models.environment.update(envPrivate, {169 data: {170 envvalue: 'private'171 }172 });173 const exportRequests = [174 { requestId: req1._id, environmentId: 'n/a' },175 { requestId: req2._id, environmentId: envPublic._id },176 { requestId: req3._id, environmentId: envPrivate._id }177 ];178 const harExport = await harUtils.exportHar(exportRequests);179 expect(harExport).toMatchObject({180 log: {181 version: '1.2',182 creator: {183 name: 'Insomnia REST Client'184 },185 entries: [186 {187 request: {188 headers: [{ name: 'X-Environment', value: '' }, { name: 'X-Request', value: '1' }]189 },190 response: {191 status: 204192 },193 comment: req1.name194 },195 {196 request: {197 headers: [198 { name: 'X-Environment', value: 'public' },199 { name: 'X-Request', value: '2' }200 ]201 },202 response: {203 status: 404204 },205 comment: req2.name206 },207 {208 request: {209 headers: [210 { name: 'X-Environment', value: 'private' },211 { name: 'X-Request', value: '3' }212 ]213 },214 response: {215 status: 500216 },217 comment: req3.name218 }219 ]220 }221 });222 });223});224describe('exportHarResponse()', () => {225 beforeEach(globalBeforeEach);226 it('exports a default har response for an empty response', async () => {227 const notFoundResponse = null;228 const harResponse = await harUtils.exportHarResponse(notFoundResponse);229 expect(harResponse).toMatchObject({230 status: 0,231 statusText: '',232 httpVersion: 'HTTP/1.1',233 content: {234 size: 0,235 mimeType: ''236 }237 });238 });239 it('exports a valid har response for a non empty response', async () => {240 const response = Object.assign(models.response.init(), {241 _id: 'res_123',242 type: models.response.type,243 parentId: 'req_123',244 modified: 0,245 created: 0,246 statusCode: 200,247 statusMessage: 'OK',248 headers: [249 { name: 'Content-Type', value: 'application/json' },250 { name: 'Content-Length', value: '2' },251 { name: 'Set-Cookie', value: 'sessionid=12345; HttpOnly; Path=/' }252 ],253 contentType: 'application/json',254 bodyPath: path.join(__dirname, '../__fixtures__/har/test-response.json')255 });256 const harResponse = await harUtils.exportHarResponse(response);257 expect(harResponse).toMatchObject({258 status: 200,259 statusText: 'OK',260 httpVersion: 'HTTP/1.1',261 cookies: [262 {263 name: 'sessionid',264 value: '12345',265 path: '/',266 httpOnly: true267 }268 ],269 headers: [270 { name: 'Content-Type', value: 'application/json' },271 { name: 'Content-Length', value: '2' },272 { name: 'Set-Cookie', value: 'sessionid=12345; HttpOnly; Path=/' }273 ],274 content: {275 size: 15,276 mimeType: 'application/json',277 text: '{"key":"value"}'278 },279 redirectURL: '',280 headersSize: -1,281 bodySize: -1282 });283 });284});285describe('exportHarWithRequest()', () => {286 beforeEach(globalBeforeEach);287 it('renders does it correctly', async () => {288 const workspace = await models.workspace.create();289 const cookies = [290 {291 creation: new Date('2016-10-05T04:40:49.505Z'),292 key: 'foo',293 value: 'barrrrr',294 expires: new Date('2096-10-12T04:40:49.000Z'),295 domain: 'google.com',296 path: '/',297 hostOnly: true,298 lastAccessed: new Date('2096-10-05T04:40:49.505Z')299 }300 ];301 const cookieJar = await models.cookieJar.getOrCreateForParentId(workspace._id);302 await models.cookieJar.update(cookieJar, {303 parentId: workspace._id,304 cookies305 });306 const request = Object.assign(models.request.init(), {307 _id: 'req_123',308 parentId: workspace._id,309 headers: [{ name: 'Content-Type', value: 'application/json' }],310 parameters: [{ name: 'foo bar', value: 'hello&world' }],311 method: 'POST',312 body: {313 text: 'foo bar'314 },315 url: 'http://google.com',316 authentication: {317 type: AUTH_BASIC,318 username: 'user',319 password: 'pass'320 }321 });322 const renderedRequest = await render.getRenderedRequest(request);323 const har = await harUtils.exportHarWithRequest(renderedRequest);324 expect(har.cookies.length).toBe(1);325 expect(har).toEqual({326 bodySize: -1,327 cookies: [328 {329 domain: 'google.com',330 expires: '2096-10-12T04:40:49.000Z',331 name: 'foo',332 path: '/',333 value: 'barrrrr'334 }335 ],336 headers: [337 { name: 'Content-Type', value: 'application/json' },338 { name: 'Authorization', value: 'Basic dXNlcjpwYXNz' }339 ],340 headersSize: -1,341 httpVersion: 'HTTP/1.1',342 method: 'POST',343 postData: {344 mimeType: '',345 params: [],346 text: 'foo bar'347 },348 queryString: [{ name: 'foo bar', value: 'hello&world' }],349 url: 'http://google.com/',350 settingEncodeUrl: true351 });352 });...
trigger-toolbox-overlay.js
Source:trigger-toolbox-overlay.js
1/* See license.txt for terms of usage */2"use strict";3module.metadata = {4 "stability": "stable"5};6// Add-on SDK7const options = require("@loader/options");8const { Cu, Ci } = require("chrome");9const { Class } = require("sdk/core/heritage");10const { defer, resolve } = require("sdk/core/promise");11const { on, off, emit } = require("sdk/event/core");12const { prefs } = require("sdk/simple-prefs");13// Platform14const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});15// DevTools16const { devtools, makeInfallible, safeRequire } = require("firebug.sdk/lib/core/devtools.js");17// https://bugzilla.mozilla.org/show_bug.cgi?id=91212118const { get: getHarOverlay } = safeRequire(devtools,19 "devtools/client/netmonitor/har/toolbox-overlay",20 "devtools/netmonitor/har/toolbox-overlay");21// Firebug SDK22const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);23const { ToolboxOverlay } = require("firebug.sdk/lib/toolbox-overlay.js");24const { Rdp } = require("firebug.sdk/lib/core/rdp.js");25const { Options } = require("firebug.sdk/lib/core/options.js");26// HARExportTrigger27const { HarDriverFront } = require("./har-driver-front");28// URL of the {@HarDriverActor} module. This module will be29// installed and loaded on the backend.30const actorModuleUrl = options.prefixURI + "lib/har-driver-actor.js";31/**32 * @overlay This object represents an overlay for the Toolbox. The33 * overlay is created when the Toolbox is opened and destroyed when34 * the Toolbox is closed. There is one instance of the overlay per35 * Toolbox, and so there can be more overlay instances created per36 * one browser session.37 *38 * This extension uses the overlay to register and attach/detach the39 * backend actor.40 */41const TriggerToolboxOverlay = Class(42/** @lends TriggerToolboxOverlay */43{44 extends: ToolboxOverlay,45 overlayId: "TriggerToolboxOverlay",46 // Initialization47 initialize: function(options) {48 ToolboxOverlay.prototype.initialize.apply(this, arguments);49 Trace.sysout("TriggerToolboxOverlay.initialize;", options);50 this.automation = options.automation;51 },52 destroy: function() {53 ToolboxOverlay.prototype.destroy.apply(this, arguments);54 Trace.sysout("TriggerToolboxOverlay.destroy;", arguments);55 },56 // Events57 onReady: function(options) {58 ToolboxOverlay.prototype.onReady.apply(this, arguments);59 Trace.sysout("TriggerToolboxOverlay.onReady;", options);60 // Platform support is needed here.61 // See: https://bugzilla.mozilla.org/show_bug.cgi?id=118488962 if (typeof getHarOverlay != "function") {63 Cu.reportError("Platform support needed, see Bug: " +64 "https://bugzilla.mozilla.org/show_bug.cgi?id=1184889");65 return;66 }67 // Call make remote to make sure the target.client exists.68 let target = this.toolbox.target;69 target.makeRemote().then(() => {70 // The 'devtools.netmonitor.har.enableAutoExportToFile' option doesn't71 // have to be set if users don't want to auto export to file after72 // every page load.73 // But, if users want to use HAR content API to trigger HAR export74 // when needed, HAR automation needs to be activated. Let's do it now75 // if 'extensions.netmonitor.har.enableAutomation' preference is true.76 if (prefs.enableAutomation && !this.automation) {77 Trace.sysout("TriggerToolboxOverlay.onReady; Init automation");78 // Initialize automation.79 let harOverlay = getHarOverlay(this.toolbox);80 if (!harOverlay) {81 TraceError.sysout("TriggerToolboxOverlay.onReady; ERROR " +82 "No HAR Overlay!");83 return;84 }85 if (!harOverlay.automation) {86 harOverlay.initAutomation();87 }88 this.automation = harOverlay.automation;89 }90 this.patchAutomation(this.automation);91 // This is a bit hacky, but the HarAutomation starts monitoring92 // after target.makeRemote() promise is resolved.93 // It's resolved after the parent target.makeRemote() (we are just within)94 // finishes.95 // So, let's register another promise handler and reset the collector96 // after the HarAutomation.startMonitoring() is actually executed.97 target.makeRemote().then(() => {98 // Make sure the collector exists. The collector is automatically99 // created when the page load begins, but the toolbox can be opened100 // in the middle of page session (after page load event).101 // And HAR API consumer might want to export any time.102 if (this.automation && !this.automation.collector) {103 this.automation.resetCollector();104 }105 });106 this.attach().then(front => {107 Trace.sysout("TriggerToolboxOverlay.onReady; HAR driver ready!");108 });109 });110 },111 /**112 * xxxHonza: this needs better platform API.113 * See also: https://github.com/firebug/har-export-trigger/issues/10114 */115 patchAutomation: function(automation) {116 if (!automation) {117 return;118 }119 let self = this;120 automation.pageLoadDone = function(response) {121 Trace.sysout("HarAutomation.patchAutomation;", response);122 if (this.collector) {123 this.collector.waitForHarLoad().then(collector => {124 self.onPageLoadDone(response);125 return this.autoExport();126 });127 }128 }129 // xxxHonza: needs testing130 /*automation.pageLoadBegin = function(response) {131 // If the persist log preference is on do not clear the HAR log.132 // It'll be collecting all data as the tab content is reloaded133 // or navigated to different location.134 // See also: https://github.com/firebug/har-export-trigger/issues/14135 let persist = Options.getPref("devtools.webconsole.persistlog");136 if (!persist) {137 this.resetCollector();138 }139 }*/140 },141 onPageLoadDone: function(response) {142 Trace.sysout("TriggerToolboxOverlay.onPageLoadDone;", response);143 this.front.pageLoadDone();144 },145 // Backend146 /**147 * Attach to the backend actor.148 */149 attach: makeInfallible(function() {150 Trace.sysout("TriggerToolboxOverlay.attach;");151 if (this.deferredAttach) {152 return this.deferredAttach.promise;153 }154 let config = {155 prefix: HarDriverFront.prototype.typeName,156 actorClass: "HarDriverActor",157 frontClass: HarDriverFront,158 moduleUrl: actorModuleUrl159 };160 this.deferredAttach = defer();161 let client = this.toolbox.target.client;162 // Register as tab actor.163 Rdp.registerTabActor(client, config).then(({registrar, front}) => {164 Trace.sysout("TriggerToolboxOverlay.attach; READY", this);165 // xxxHonza: Unregister at shutdown166 this.registrar = registrar;167 this.front = front;168 this.front.setToken(prefs.contentAPIToken).then(() => {169 emit(this, "attach", front);170 // Listen to API calls. Every time the page executes171 // HAR API, corresponding event is sent from the backend.172 front.on("trigger-export", this.triggerExport.bind(this));173 front.on("clear", this.clear.bind(this));174 this.deferredAttach.resolve(front);175 });176 });177 return this.deferredAttach.promise;178 }),179 // Content API180 /**181 * Handle RDP event from the backend. HAR.triggerExport() has been182 * executed in the page and existing data in the Network panel183 * need to be exported.184 */185 triggerExport: function(data) {186 Trace.sysout("TriggerToolboxOverlay.triggerExport;", data);187 if (!this.automation) {188 let pref1 = "devtools.netmonitor.har.enableAutoExportToFile";189 let pref2 = "extensions.netmonitor.har.enableAutomation";190 if (!this.automation) {191 Cu.reportError("You need to set '" + pref1 + "' or '" + pref2 +192 "' pref to enable HAR export through the API " +193 "(browser restart is required)");194 }195 return;196 }197 if (!this.automation.collector) {198 Cu.reportError("The HAR collector doesn't exist. Page reload required.");199 return;200 }201 // Trigger HAR export now! Use executeExport() not triggerExport()202 // since we don't want to have the default name automatically provided.203 this.automation.executeExport(data).then(jsonString => {204 var har = jsonString;205 try {206 if (jsonString) {207 har = JSON.parse(jsonString);208 }209 } catch (err) {210 Trace.sysout("TriggerToolboxOverlay.triggerExport; ERROR " +211 "Failed to parse HAR log " + err);212 }213 // Send event back to the backend notifying that it has214 // finished. If 'getData' is true include also the HAR string.215 // The content API call will be resolved as soon as the packet216 // arrives on the backend.217 if (data.id) {218 this.front.exportDone({219 id: data.id,220 data: data.getData ? jsonString : undefined,221 });222 }223 });224 },225 /**226 * Handle RDP event from the backend. HAR.clear() has been227 * executed in the page and the Network panel content228 * needs to be cleared.229 */230 clear: function() {231 Trace.sysout("TriggerToolboxOverlay.clear;");232 let panel = this.toolbox.getPanel("netmonitor");233 // Clean up also the HAR collector.234 this.automation.resetCollector();235 // Clear the Network panel content. The panel doesn't236 // have to exist if the user doesn't select it yet.237 if (panel) {238 let view = panel.panelWin.NetMonitorView;239 view.RequestsMenu.clear();240 };241 },242});243// Exports from this module...
browserContextDispatcher.js
Source:browserContextDispatcher.js
...200 }201 async tracingStop(params) {202 await this._context.tracing.stop();203 }204 async harExport(params) {205 var _this$_context$_harRe;206 const artifact = await ((_this$_context$_harRe = this._context._harRecorder) === null || _this$_context$_harRe === void 0 ? void 0 : _this$_context$_harRe.export());207 if (!artifact) throw new Error('No HAR artifact. Ensure record.harPath is set.');208 return {209 artifact: new _artifactDispatcher.ArtifactDispatcher(this._scope, artifact)210 };211 }212}...
main.js
Source:main.js
1/* See license.txt for terms of usage */2"use strict";3module.metadata = {4 "stability": "stable"5};6// Add-on SDK7const { Cu, Ci } = require("chrome");8const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);9const { ToolboxChrome } = require("firebug.sdk/lib/toolbox-chrome.js");10// HARExportTrigger11const { TriggerToolboxOverlay } = require("./trigger-toolbox-overlay.js");12const { TriggerToolbox } = require("./trigger-toolbox.js");13/**14 * Entry point of the extension. Both 'main' and 'onUnload' methods are15 * exported from this module and executed automatically by Add-ons SDK.16 */17function main(options, callbacks) {18 ToolboxChrome.initialize(options);19 ToolboxChrome.registerToolboxOverlay(TriggerToolboxOverlay);20 TriggerToolbox.initialize();21}22/**23 * Executed on browser shutdown or when the extension is24 * uninstalled/removed/disabled.25 */26function onUnload(reason) {27 ToolboxChrome.unregisterToolboxOverlay(TriggerToolboxOverlay);28 TriggerToolbox.shutdown(reason);29 ToolboxChrome.shutdown(reason);30}31// Exports from this module32exports.main = main;...
har-driver-front.js
Source:har-driver-front.js
1/* See license.txt for terms of usage */2"use strict";3module.metadata = {4 "stability": "stable"5};6// Add-on SDK7const { Cu } = require("chrome");8// DevTools9const DevTools = require("firebug.sdk/lib/core/devtools.js");10const { Front, FrontClass } = DevTools.Protocol;11// Firebug SDK12const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);13// HARExportTrigger14const { HarDriverActor } = require("./har-driver-actor.js");15/**16 * @front This object represents client side for the backend actor.17 *18 * Read more about Protocol API:19 * https://github.com/mozilla/gecko-dev/blob/master/toolkit/devtools/server/docs/protocol.js.md20 */21var HarDriverFront = FrontClass(HarDriverActor,22/** @lends HarDriverFront */23{24 // Initialization25 initialize: function(client, form) {26 Front.prototype.initialize.apply(this, arguments);27 Trace.sysout("HarDriverFront.initialize;", this);28 this.actorID = form[HarDriverActor.prototype.typeName];29 this.manage(this);30 },31});32// Exports from this module...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'screenshot.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'screenshot.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'screenshot.png' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'screenshot.png' });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch({ headless: false });36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'screenshot.png' });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch({ headless: false });44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const {chromium} = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const har = await page.evaluate(() => window.harExport());8 fs.writeFileSync('har.json', JSON.stringify(har));9 await browser.close();10})();11{12 "log": {13 "creator": {14 },15 {16 "pageTimings": {17 }18 }19 {20 "request": {21 {22 "value": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"23 },24 {25 },26 {27 "value": "en-US,en;q=0.9"28 },29 {30 },31 {32 },33 {34 },35 {36 "value": "Mozilla/5.0 (Macintosh
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const har = await page.harExport();6 console.log(har);7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const har = await page.harExport();14 console.log(har);15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 const har = await page.harExport();22 console.log(har);23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();29 const har = await page.harExport();30 console.log(har);31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const page = await browser.newPage();37 const har = await page.harExport();38 console.log(har);39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const page = await browser.newPage();45 const har = await page.harExport();46 console.log(har);47 await browser.close();48})();49const { chromium } =
Using AI Code Generation
1const harExport = require('har-export');2const playwright = require('playwright');3(async () => {4 const browser = await playwright['chromium'].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await harExport(page);8 const har = await page.har();9 console.log(har);10 await browser.close();11})();12const harExport = require('har-export');13const playwright = require('playwright');14(async () => {15 const browser = await playwright['chromium'].launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await harExport(page);19 const har = await page.har();20 console.log(har);21 await browser.close();22})();23const playwright = require('playwright');24(async () => {25 const browser = await playwright['chromium'].launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.screenshot({ path: `example.png` });29 await browser.close();30})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const harExport = require('har-export');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const har = await harExport(page);7 console.log(har);8 await browser.close();9})();10const playwright = require('playwright');11(async () => {12 const browser = await playwright.chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const har = await page.harExport();16 console.log(har);17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright.firefox.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 const har = await page.harExport();25 console.log(har);26 await browser.close();27})();28const playwright = require('playwright');29(async () => {30 const browser = await playwright.webkit.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 const har = await page.harExport();34 console.log(har);35 await browser.close();36})();37const playwright = require('playwright');38(async () => {39 const browser = await playwright.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const har = await page.harExport();43 console.log(har);44 await browser.close();45})();46const playwright = require('playwright');47(async () => {48 const browser = await playwright.launch();49 const context = await browser.newContext();50 const page = await context.newPage();51 const har = await page.harExport();52 console.log(har);53 await browser.close();54})();
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.screenshot({path: 'google.png'});7 await page.harExport({path: 'google.har'});8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require("playwright-chromium");2const browser = await chromium.launch();3const context = await browser.newContext();4const page = await context.newPage();5await page.harExport({ path: "test.har" });6await browser.close();7{8 "log": {9 "creator": {
Using AI Code Generation
1const playwright = require('playwright');2const fs = require('fs');3(async () => {4 const browser = await playwright.chromium.launch({headless: false});5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.route('**', route => route.fulfill({body: 'foo'}));8 await page.waitForTimeout(5000);9 const har = await page.harExport();10 fs.writeFileSync('har.json', JSON.stringify(har));11 await browser.close();12})();13{14 "log": {15 "creator": {16 },17 {18 "pageTimings": {19 }20 }21 {22 "request": {23 {24 "value": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"25 },26 {27 },28 {29 "value": "en-US,en;q=0.9"30 },31 {32 },33 {34 },35 {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const page = await browser.newPage();6 await page.route('**/*', route => route.fulfill({7 }));8 await page.click('text=Sign in');9 await page.fill('#identifierId', 'test');10 await page.click('text=Next');11 await page.fill('input[type="password"]', 'test');12 await page.click('text=Next');13 await page.waitForNavigation();14 await page.click('text=Sign in');15 await page.click('text=Next');16 await page.click('text=Next');17 await page.context().addInitScript(() => {18 window.harExport = function () {19 return JSON.stringify(window.performance.getEntriesByType('resource'));20 };21 });22 await page.evaluate(() => {23 window.performance.clearResourceTimings();24 });
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!!