Best JavaScript code snippet using playwright-internal
streamListener.js
Source:streamListener.js  
1/*2    ***** BEGIN LICENSE BLOCK *****3    4    Copyright © 2009 Center for History and New Media5                     George Mason University, Fairfax, Virginia, USA6                     http://zotero.org7    8    This file is part of Zotero.9    10    Zotero is free software: you can redistribute it and/or modify11    it under the terms of the GNU Affero General Public License as published by12    the Free Software Foundation, either version 3 of the License, or13    (at your option) any later version.14    15    Zotero is distributed in the hope that it will be useful,16    but WITHOUT ANY WARRANTY; without even the implied warranty of17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the18    GNU Affero General Public License for more details.19    20    You should have received a copy of the GNU Affero General Public License21    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.22    23    ***** END LICENSE BLOCK *****24*/25/**26 * Stream listener that can handle both download and upload requests27 *28 * Possible properties of data object:29 *   - onStart: f(request)30 *   - onProgress:  f(request, progress, progressMax)31 *   - onStop:  f(request, status, response)32 *   - onCancel:  f(request, status)33 *   - streams: array of streams to close on completion34 */35Zotero.Sync.Storage.StreamListener = function (data) {36	this._data = data;37}38Zotero.Sync.Storage.StreamListener.prototype = {39	_channel: null,40	41	// nsIProgressEventSink42	onProgress: function (request, context, progress, progressMax) {43		Zotero.debug("onProgress with " + progress + "/" + progressMax);44		this._onProgress(request, progress, progressMax);45	},46	47	onStatus: function (request, context, status, statusArg) {48		Zotero.debug('onStatus with ' + status);49	},50	51	// nsIRequestObserver52	// Note: For uploads, this isn't called until data is done uploading53	onStartRequest: function (request, context) {54		Zotero.debug('onStartRequest');55		this._response = "";56		57		this._onStart(request);58	},59	60	onStopRequest: function (request, context, status) {61		Zotero.debug('onStopRequest with ' + status);62		63		// Some errors from https://developer.mozilla.org/en-US/docs/Table_Of_Errors64		var msg = "";65		switch (status) {66		// Normal67		case 0:68			break;69		70		// NS_BINDING_ABORTED71		case 0x804b0002:72			msg = "Request cancelled";73			break;74		75		// NS_ERROR_NET_INTERRUPT76		case 0x804B0047:77			msg = "Request interrupted";78			break;79		80		// NS_ERROR_NET_TIMEOUT81		case 0x804B000E:82			msg = "Request timed out";83			break;84		85		default:86			msg = "Request failed";87			break;88		}89		90		if (msg) {91			msg += " in Zotero.Sync.Storage.StreamListener.onStopRequest() (" + status + ")";92			Components.utils.reportError(msg);93			Zotero.debug(msg, 1);94		}95		96		this._onStop(request, status);97	},98	99	// nsIWebProgressListener100	onProgressChange: function (wp, request, curSelfProgress,101			maxSelfProgress, curTotalProgress, maxTotalProgress) {102		//Zotero.debug("onProgressChange with " + curTotalProgress + "/" + maxTotalProgress);103		104		// onProgress gets called too, so this isn't necessary105		//this._onProgress(request, curTotalProgress, maxTotalProgress);106	},107	108	onStateChange: function (wp, request, stateFlags, status) {109		Zotero.debug("onStateChange with " + stateFlags);110		111		if (stateFlags & Components.interfaces.nsIWebProgressListener.STATE_IS_REQUEST) {112			if (stateFlags & Components.interfaces.nsIWebProgressListener.STATE_START) {113				this._onStart(request);114			}115			else if (stateFlags & Components.interfaces.nsIWebProgressListener.STATE_STOP) {116				this._onStop(request, status);117			}118		}119	},120	121	onStatusChange: function (progress, request, status, message) {122		Zotero.debug("onStatusChange with '" + message + "'");123	},124	onLocationChange: function () {125		Zotero.debug('onLocationChange');126	},127	onSecurityChange: function () {128		Zotero.debug('onSecurityChange');129	},130	131	// nsIStreamListener132	onDataAvailable: function (request, context, stream, sourceOffset, length) {133		Zotero.debug('onDataAvailable');134		var scriptableInputStream = 135			Components.classes["@mozilla.org/scriptableinputstream;1"]136				.createInstance(Components.interfaces.nsIScriptableInputStream);137		scriptableInputStream.init(stream);138		139		var data = scriptableInputStream.read(length);140		Zotero.debug(data);141		this._response += data;142	},143	144	// nsIChannelEventSink145	//146	// If this._data.onChannelRedirect exists, it should return a promise resolving to true to147	// follow the redirect or false to cancel it148	onChannelRedirect: Zotero.Promise.coroutine(function* (oldChannel, newChannel, flags) {149		Zotero.debug('onChannelRedirect');150		151		if (this._data && this._data.onChannelRedirect) {152			let result = yield this._data.onChannelRedirect(oldChannel, newChannel, flags);153			if (!result) {154				oldChannel.cancel(Components.results.NS_BINDING_ABORTED);155				newChannel.cancel(Components.results.NS_BINDING_ABORTED);156				Zotero.debug("Cancelling redirect");157				// TODO: Prevent onStateChange error158				return false;159			}160		}161		162		// if redirecting, store the new channel163		this._channel = newChannel;164	}),165	166	asyncOnChannelRedirect: function (oldChan, newChan, flags, redirectCallback) {167		Zotero.debug('asyncOnRedirect');168		169		this.onChannelRedirect(oldChan, newChan, flags)170		.then(function (result) {171			redirectCallback.onRedirectVerifyCallback(172				result ? Components.results.NS_SUCCEEDED : Components.results.NS_FAILED173			);174		})175		.catch(function (e) {176			Zotero.logError(e);177			redirectCallback.onRedirectVerifyCallback(Components.results.NS_FAILED);178		});179	},180	181	// nsIHttpEventSink182	onRedirect: function (oldChannel, newChannel) {183		Zotero.debug('onRedirect');184		185		var newURL = Zotero.HTTP.getDisplayURI(newChannel.URI).spec;186		Zotero.debug("Redirecting to " + newURL);187	},188	189	190	//191	// Private methods192	//193	_onStart: function (request) {194		Zotero.debug('Starting request');195		if (this._data && this._data.onStart) {196			this._data.onStart(request);197		}198	},199	200	_onProgress: function (request, progress, progressMax) {201		if (this._data && this._data.onProgress) {202			this._data.onProgress(request, progress, progressMax);203		}204	},205	206	_onStop: function (request, status) {207		var cancelled = status == 0x804b0002; // NS_BINDING_ABORTED208		209		if (!cancelled && status == 0 && request instanceof Components.interfaces.nsIHttpChannel) {210			request.QueryInterface(Components.interfaces.nsIHttpChannel);211			try {212				status = request.responseStatus;213			}214			catch (e) {215				Zotero.debug("Request responseStatus not available", 1);216				status = 0;217			}218			Zotero.debug('Request ended with status code ' + status);219			request.QueryInterface(Components.interfaces.nsIRequest);220		}221		else {222			Zotero.debug('Request ended with status ' + status);223			status = 0;224		}225		226		if (this._data.streams) {227			for (let stream of this._data.streams) {228				stream.close();229			}230		}231		232		if (cancelled) {233			if (this._data.onCancel) {234				this._data.onCancel(request, status);235			}236		}237		else {238			if (this._data.onStop) {239				this._data.onStop(request, status, this._response);240			}241		}242		243		this._channel = null;244	},245	246	// nsIInterfaceRequestor247	getInterface: function (iid) {248		try {249			return this.QueryInterface(iid);250		}251		catch (e) {252			throw Components.results.NS_NOINTERFACE;253		}254	},255	256	QueryInterface: function(iid) {257		if (iid.equals(Components.interfaces.nsISupports) ||258				iid.equals(Components.interfaces.nsIInterfaceRequestor) ||259				iid.equals(Components.interfaces.nsIChannelEventSink) || 260				iid.equals(Components.interfaces.nsIProgressEventSink) ||261				iid.equals(Components.interfaces.nsIHttpEventSink) ||262				iid.equals(Components.interfaces.nsIStreamListener) ||263				iid.equals(Components.interfaces.nsIWebProgressListener)) {264			return this;265		}266		throw Components.results.NS_NOINTERFACE;267	},268	269	_safeSpec: function (uri) {270		return uri.scheme + '://' + uri.username + ':********@'271			+ uri.hostPort + uri.pathQueryRef272	},...policy.js
Source:policy.js  
1/* ***** BEGIN LICENSE BLOCK *****2 * Version: MPL 1.13 *4 * The contents of this file are subject to the Mozilla Public License Version5 * 1.1 (the "License"); you may not use this file except in compliance with6 * the License. You may obtain a copy of the License at7 * http://www.mozilla.org/MPL/8 *9 * Software distributed under the License is distributed on an "AS IS" basis,10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License11 * for the specific language governing rights and limitations under the12 * License.13 *14 * The Original Code is Adblock Plus.15 *16 * The Initial Developer of the Original Code is17 * Wladimir Palant.18 * Portions created by the Initial Developer are Copyright (C) 2006-200919 * the Initial Developer. All Rights Reserved.20 *21 * Contributor(s):22 * 2009-2010: Wang Congming <lovelywcm@gmail.com> Modified for AutoProxy.23 *24 * ***** END LICENSE BLOCK ***** */25/**26 * Content policy implementation.27 * This file is included from AutoProxy.js.28 */29var effectiveTLD = Cc["@mozilla.org/network/effective-tld-service;1"].getService(Ci.nsIEffectiveTLDService);30const ok = Ci.nsIContentPolicy.ACCEPT;31var policy =32{33  /**34   * Map of content type identifiers by their name.35   * @type Object36   */37  type: null,38  /**39   * Map of content type names by their identifiers (reverse of type map).40   * @type Object41   */42  typeDescr: null,43  /**44   * Map of localized content type names by their identifiers.45   * @type Object46   */47  localizedDescr: null,48  /**49   * Assigned in shouldLoad() & used by autoMatching().50   * Since autoMatching is called by applyFilter,51   * but we can't get such information within applyFilter(?).52   */53  Wnd: null,        // nsIDOMWindow54  Node: null,       // nsIDOMElement55  ContentType: "",  // String56  ContentURI: null, // nsIURI57  init: function() {58    var types = ["OTHER", "SCRIPT", "IMAGE", "STYLESHEET", "OBJECT", "SUBDOCUMENT", "DOCUMENT", "XBL", "PING", "XMLHTTPREQUEST", "OBJECT_SUBREQUEST", "DTD", "FONT", "MEDIA"];59    // type constant by type description and type description by type constant60    this.type = {};61    this.typeDescr = {};62    this.localizedDescr = {};63    var iface = Ci.nsIContentPolicy;64    for each (let typeName in types)65    {66      if ("TYPE_" + typeName in iface)67      {68        this.type[typeName] = iface["TYPE_" + typeName];69        this.typeDescr[this.type[typeName]] = typeName;70        this.localizedDescr[this.type[typeName]] = aup.getString("type_label_" + typeName.toLowerCase());71      }72    }73    this.type.BACKGROUND = 0xFFFE;74    this.typeDescr[0xFFFE] = "BACKGROUND";75    this.localizedDescr[0xFFFE] = aup.getString("type_label_background");76  },77  /**78   * Checks whether a node should be proxyed according to rules79   * @param location {nsIURI}80   * @return {Boolean} true if the node should be proxyed81   */82  autoMatching: function(location) {83    var match = null, docDomain = "extension", thirdParty = false, contentType = 3;84    var wnd, node, locationText = location.spec;85    if (location == this.ContentURI) {86      wnd = this.Wnd; node = this.Node; contentType = this.ContentType;87      // Data loaded by plugins should be attached to the document88      if ((contentType == this.type.OTHER || contentType == this.type.OBJECT_SUBREQUEST) && node instanceof Element)89        node = node.ownerDocument;90      // Fix type for background images91      if (contentType == this.type.IMAGE && node.nodeType == Node.DOCUMENT_NODE)92        contentType = this.type.BACKGROUND;93      // Fix type for objects misrepresented as frames or images94      if (contentType != this.type.OBJECT && (node instanceof Ci.nsIDOMHTMLObjectElement || node instanceof Ci.nsIDOMHTMLEmbedElement))95        contentType = this.type.OBJECT;96      docDomain = wnd.location.host;97      thirdParty = this.isThirdParty(location, docDomain);98    }99    match = whitelistMatcher.matchesAny(locationText, this.typeDescr[contentType] || "", docDomain, thirdParty);100    if (match == null)101      match = blacklistMatcher.matchesAny(locationText, this.typeDescr[contentType] || "", docDomain, thirdParty);102    // Store node data.103    // Skip this step if the request is established by a Firefox extension104    //   * no sidebar window can be used to display extension's http request;105    //   * shouldLoad() doesn't check extension's request, any way to do this?106    //     * just like onChannelRedirect() did for 301/302 redirection.107    if (location == this.ContentURI) {108      var data = RequestList.getDataForWindow(wnd);109      data.addNode(node, contentType, docDomain, thirdParty, locationText, match);110    }111    if (match && arguments.length == 1)112      filterStorage.increaseHitCount(match);113    return match;114  },115  /**116   * Checks whether the location's origin is different from document's origin.117   */118  isThirdParty: function(/**nsIURI*/location, /**String*/ docDomain) /**Boolean*/119  {120    if (!location || !docDomain)121      return true;122    try123    {124      return effectiveTLD.getBaseDomain(location) != effectiveTLD.getBaseDomainFromHost(docDomain);125    }126    catch (e)127    {128      // EffectiveTLDService throws on IP addresses, just compare the host name129      let host = "";130      try131      {132        host = location.host;133      } catch (e) {}134      return host != docDomain;135    }136  },137  //138  // nsISupports interface implementation139  //140  QueryInterface: aup.QueryInterface,141  //142  // nsIContentPolicy interface implementation143  //144  shouldLoad: function(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra)145  {146    if (proxy.isProxyableScheme(contentLocation)) {147      // Interpret unknown types as "other"148      if (!(contentType in this.typeDescr))149        contentType = this.type.OTHER;150      this.Wnd = getWindow(node);151      this.Node = node;152      this.ContentType = contentType;153      this.ContentURI = unwrapURL(contentLocation);154    }155    return ok;156  },157  shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra)158  {159    return ok;160  },161  //162  // nsIChannelEventSink interface implementation163  //164  onChannelRedirect: function(oldChannel, newChannel, flags)165  {166    try {167      // Look for the request both in the origin window and in its parent (for frames)168      let contexts = [getRequestWindow(newChannel)];169      if (!contexts[0])170        contexts.pop();171      else if (contexts[0] && contexts[0].parent != contexts[0])172        contexts.push(contexts[0].parent);173      else if (contexts[0] && contexts[0].parent == contexts[0])174      {175        contexts.push(Cc["@mozilla.org/appshell/window-mediator;1"]176                .getService(Ci.nsIWindowMediator)177                .getMostRecentWindow("navigator:browser"));178        contexts.shift();179      }180      let info = null;181      for each (let context in contexts)182      {183        // Did we record the original request in its own window?184        let data = RequestList.getDataForWindow(context, true);185        if (data)186          info = data.getURLInfo(oldChannel.originalURI.spec);187        if (info)188        {189          let nodes = info.nodes;190          let node = (nodes.length > 0 ? nodes[nodes.length - 1] : context.document);191          this.Wnd = context;192          this.Node = node;193          this.ContentType = info.type;194          this.ContentURI = newChannel.URI;195          this.autoMatching(newChannel.URI, true);196          return;197        }198      }199    }200    catch (e)201    {202      // We shouldn't throw exceptions here - this will prevent the redirect.203      dump("AutoProxy: Unexpected error in policy.onChannelRedirect: " + e + "\n");204    }205  },206  asyncOnChannelRedirect: function(oldChannel, newChannel, flags, cb)207  {208    this.onChannelRedirect(oldChannel, newChannel, flags);209    cb.onRedirectVerifyCallback(0);210  }211};...test_history_redirects.js
Source:test_history_redirects.js  
1/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */2/* vim:set ts=2 sw=2 sts=2 et: */3/* Any copyright is dedicated to the Public Domain.4   http://creativecommons.org/publicdomain/zero/1.0/ */5/* Tests history redirects handling */6let hs = Cc["@mozilla.org/browser/nav-history-service;1"].7         getService(Ci.nsINavHistoryService);8let bh = hs.QueryInterface(Ci.nsIBrowserHistory);9const PERMA_REDIR_PATH = "/permaredir";10const TEMP_REDIR_PATH = "/tempredir";11const FOUND_PATH = "/found";12const HTTPSVR = new HttpServer();13const PORT = 4444;14HTTPSVR.registerPathHandler(PERMA_REDIR_PATH, permaRedirHandler);15HTTPSVR.registerPathHandler(TEMP_REDIR_PATH, tempRedirHandler);16HTTPSVR.registerPathHandler(FOUND_PATH, foundHandler);17const EXPECTED_SESSION_ID = 1;18const STATUS = {19  REDIRECT_PERMANENT: [301, "Moved Permanently"],20  REDIRECT_TEMPORARY: [302, "Moved"],21  FOUND: [200, "Found"],22}23const PERMA_REDIR_URL = "http://localhost:" + PORT + PERMA_REDIR_PATH;24const TEMP_REDIR_URL = "http://localhost:" + PORT + TEMP_REDIR_PATH;25const FOUND_URL = "http://localhost:" + PORT + FOUND_PATH;26// PERMANENT REDIRECT27function permaRedirHandler(aMeta, aResponse) {28  // Redirect permanently to TEMP_REDIR_URL29  PathHandler(aMeta, aResponse, "REDIRECT_PERMANENT", TEMP_REDIR_URL);30}31// TEMPORARY REDIRECT32function tempRedirHandler(aMeta, aResponse) {33  // Redirect temporarily to FOUND_URL34  PathHandler(aMeta, aResponse, "REDIRECT_TEMPORARY", FOUND_URL);35}36// FOUND37function foundHandler(aMeta, aResponse) {38  PathHandler(aMeta, aResponse, "FOUND");39}40function PathHandler(aMeta, aResponse, aChannelEvent, aRedirURL) {41  aResponse.setStatusLine(aMeta.httpVersion,42                          STATUS[aChannelEvent][0],   // Code43                          STATUS[aChannelEvent][1]);  // Text44  if (aRedirURL)45    aResponse.setHeader("Location", aRedirURL, false);46  //aResponse.setHeader("Content-Type", "text/html", false);47  let body = STATUS[aChannelEvent][1] + "\r\n";48  aResponse.bodyOutputStream.write(body, body.length);49}50function run_test() {51  do_test_pending();52  HTTPSVR.start(PORT);53  var chan = NetUtil.ioService54                    .newChannelFromURI(uri("http://localhost:4444/permaredir"));55  var listener = new ChannelListener();56  chan.notificationCallbacks = listener;57  chan.asyncOpen(listener, null);58  // The test will continue on onStopRequest.59}60function continue_test() {61  let stmt = DBConn().createStatement(62    "SELECT v.id, h.url, v.from_visit, v.visit_date, v.visit_type, v.session " +63    "FROM moz_historyvisits v " +64    "JOIN moz_places h on h.id = v.place_id " +65    "ORDER BY v.id ASC");66  const EXPECTED = [67    { id: 1,68      url: PERMA_REDIR_URL,69      from_visit: 0,70      visit_type: Ci.nsINavHistoryService.TRANSITION_LINK,71      session: EXPECTED_SESSION_ID },72    { id: 2,73      url: TEMP_REDIR_URL,74      from_visit: 1,75      visit_type: Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT,76      session: EXPECTED_SESSION_ID },77    { id: 3,78      url: FOUND_URL,79      from_visit: 2,80      visit_type: Ci.nsINavHistoryService.TRANSITION_REDIRECT_TEMPORARY,81      session: EXPECTED_SESSION_ID },82  ];83  try {84    while(stmt.executeStep()) {85      let comparator = EXPECTED.shift();86      do_log_info("Checking that '" + comparator.url +87                  "' was entered into the DB correctly");88      do_check_eq(stmt.row.id, comparator.id);89      do_check_eq(stmt.row.url, comparator.url);90      do_check_eq(stmt.row.from_visit, comparator.from_visit);91      do_check_eq(stmt.row.visit_type, comparator.visit_type);92      do_check_eq(stmt.row.session, comparator.session);93    }94  }95  finally {96    stmt.finalize();97  }98  HTTPSVR.stop(do_test_finished);99}100/**101 * Read count bytes from stream and return as a String object102 */103function read_stream(stream, count) {104  /* assume stream has non-ASCII data */105  var wrapper =106      Components.classes["@mozilla.org/binaryinputstream;1"]107                .createInstance(Components.interfaces.nsIBinaryInputStream);108  wrapper.setInputStream(stream);109  /* JS methods can be called with a maximum of 65535 arguments, and input110     streams don't have to return all the data they make .available() when111     asked to .read() that number of bytes. */112  var data = [];113  while (count > 0) {114    var bytes = wrapper.readByteArray(Math.min(65535, count));115    data.push(String.fromCharCode.apply(null, bytes));116    count -= bytes.length;117    if (bytes.length == 0)118      do_throw("Nothing read from input stream!");119  }120  return data.join('');121}122function ChannelListener() {123}124ChannelListener.prototype = {125  _buffer: "",126  _got_onstartrequest: false,127  _got_onchannelredirect: false,128  QueryInterface: XPCOMUtils.generateQI([129    Ci.nsIStreamListener,130    Ci.nsIRequestObserver,131    Ci.nsIInterfaceRequestor,132    Ci.nsIChannelEventSink,133  ]),134  // nsIInterfaceRequestor135  getInterface: function (aIID) {136    try {137      return this.QueryInterface(aIID);138    } catch (e) {139      throw Components.results.NS_NOINTERFACE;140    }141  },142  onStartRequest: function(request, context) {143    do_log_info("onStartRequest");144    this._got_onstartrequest = true;145  },146  onDataAvailable: function(request, context, stream, offset, count) {147    this._buffer = this._buffer.concat(read_stream(stream, count));148  },149  onStopRequest: function(request, context, status) {150    do_log_info("onStopRequest");151    this._got_onstoprequest++;152    let success = Components.isSuccessCode(status);153    do_check_true(success);154    do_check_true(this._got_onstartrequest);155    do_check_true(this._got_onchannelredirect);156    do_check_true(this._buffer.length > 0);157    continue_test();158  },159  // nsIChannelEventSink160  asyncOnChannelRedirect: function (aOldChannel, aNewChannel, aFlags, callback) {161    do_log_info("onChannelRedirect");162    this._got_onchannelredirect = true;163    callback.onRedirectVerifyCallback(Components.results.NS_OK);164  },...channel-event-sink.js
Source:channel-event-sink.js  
...29      ChannelEventSinkFactory.unregister();30    }31  },32  // eslint-disable-next-line no-shadow33  asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) {34    for (const collector of this.collectors) {35      try {36        collector.onChannelRedirect(oldChannel, newChannel, flags);37      } catch (ex) {38        console.error(39          "StackTraceCollector.onChannelRedirect threw an exception",40          ex41        );42      }43    }44    callback.onRedirectVerifyCallback(Cr.NS_OK);45  },46};47const ChannelEventSinkFactory = XPCOMUtils.generateSingletonFactory(...ChannelItem.js
Source:ChannelItem.js  
1class ChannelItem {2    constructor(data) {3        this.element = this.getElement(data);4        this.element.addEventListener(5            "click",6            e => this.onChannelRedirect(e),7            false8        );9        this.element.classList.add("ChannelItem");10        this.data = data;11    }12    onChannelRedirect(e) {13        e.preventDefault(e);14        e.stopPropagation(e);15        location.href = `channel.html?id=${this.id}`;16    }17    getElement(data) {18        var html = `  19        <div class="column-in-channels channel-no-0" style="width: 142px; height:142px;">20            <div class="card-channel">21                <a href="/channel.html?id=${data.snippet.channelId}">22                    <div class="channel-image" style="background-image: url(${23                        data.snippet.thumbnails.high.url24                    })"></div>25                </a>26                <h3 class="card-title"><a href="/channel.html?id=${27                    data.snippet.channelId28                }">${data.snippet.channelTitle}</a></h3>29                <p><span class="small silver"> </span></p>30                <div class="buffer-15"></div>31            </div>32        </div>33        `;34        return html.toHtmlElement();35    }36    setChannelDetails(data) {37        let thumbNailContainer = this.element.querySelector(38            ".image-round .image-channel"39        );40        thumbNailContainer.src = data.items[0].snippet.thumbnails.default.url;41    }...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.route('**/*', route => route.continue());7  await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11  const browser = await chromium.launch();12  const context = await browser.newContext();13  const page = await context.newPage();14  await page.route('**/*', route => route.continue());15  await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19  const browser = await chromium.launch();20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.route('**/*', route => route.continue());23  await browser.close();24})();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.route('**', route => {7    console.log(route.request().url());8    route.continue();9  });10  await browser.close();11})();12const {chromium} = require('playwright');13(async () => {14  const browser = await chromium.launch();15  const context = await browser.newContext();16  const page = await context.newPage();17  await page.route('**', route => {18    console.log(route.request().url());19    route.continue();20  });21  await page.on('request', request => {22    if (request.url().includes('google')) {23      request.continue({24      });25    }26  });27  await browser.close();28})();29const {chromium} = require('playwright');30(async () => {31  const browser = await chromium.launch();32  const context = await browser.newContext();33  const page = await context.newPage();34  await page.route('**', route => {35    console.log(route.request().url());36    route.continue();37  });38  await page._client.send('Fetch.enable', {39      {40      },41  });42  await page._client.on('Fetch.requestPaused', async ({requestId}) => {43    const request = await page._client.send('Fetch.continueRequest', {44    });45  });46  await browser.close();47})();Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch({ headless: false });4  const page = await browser.newPage();5  const client = await page.context().newCDPSession(page);6  await client.send('Network.enable');7  await client.on('Network.responseReceived', (params) => {8    console.log('Network.responseReceived', params);9  });10  await client.on('Network.requestWillBeSent', (params) => {11    console.log('Network.requestWillBeSent', params);12  });13  await client.on('Network.onRequestWillBeSentExtraInfo', (params) => {14    console.log('Network.onRequestWillBeSentExtraInfo', params);15  });16  await client.on('Network.onBeforeRedirect', (params) => {17    console.log('Network.onBeforeRedirect', params);18  });19  await client.on('Network.onResponseReceivedExtraInfo', (params) => {20    console.log('Network.onResponseReceivedExtraInfo', params);21  });22  await client.on('Network.dataReceived', (params) => {23    console.log('Network.dataReceived', params);24  });25  await client.on('Network.loadingFinished', (params) => {26    console.log('Network.loadingFinished', params);27  });28  await client.on('Network.loadingFailed', (params) => {29    console.log('Network.loadingFailed', params);30  });31  await client.on('Network.onRequestServedFromCache', (params) => {32    console.log('Network.onRequestServedFromCache', params);33  });34  await client.on('Network.onRequestServedFromMemoryCache', (params) => {35    console.log('Network.onRequestServedFromMemoryCache', params);36  });37  await client.on('Network.onRequestServedFromDiskCache', (params) => {38    console.log('Network.onRequestServedFromDiskCache', params);39  });40  await client.on('Network.onLoadingFinished', (params) => {41    console.log('Network.onLoadingFinished', params);42  });43  await client.on('Network.onLoadingFailed', (params) => {44    console.log('Network.onLoadingFailed', params);45  });46  await client.on('Network.onResponseReceived', (params) => {47    console.log('Network.onResponseReceived', params);48  });49  await client.on('Network.onDataReceived', (params) => {50    console.log('Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3  const browser = await chromium.launch({headless: false});4  const page = await browser.newPage();5  await page.route('**', route => route.continue());6  await browser.close();7})();8module.exports = {9  use: {10    launchOptions: {11    },12  },13    {14      use: {15      },16    },17    {18      use: {19      },20    },21    {22      use: {23      },24    },25    {26      use: {27      },28    },29};30module.exports = {31};32module.exports = {33  use: {34    launchOptions: {35    },36  },37    {38      use: {39      },40    },41    {42      use: {43      },44    },45    {46      use: {47      },48    },49    {50      use: {51      },52    },53};54module.exports = {Using AI Code Generation
1const { chromium } = require('playwright');2const { EventEmitter } = require('events');3const events = new EventEmitter();4(async () => {5  const browser = await chromium.launch({ headless: false });6  const context = await browser.newContext({ ignoreHTTPSErrors: true });7  await context.route('**/*', route => {8    const url = route.request().url();9    events.emit('request', url);10    route.continue();11  });12  const page = await context.newPage();13  console.log(response.status());14  await browser.close();15})();16events.on('request', (url) => {17  console.log(url);18});19const { chromium } = require('playwright');20const { EventEmitter } = require('events');21const events = new EventEmitter();22(async () => {23  const browser = await chromium.launch({ headless: false });24  const context = await browser.newContext({ ignoreHTTPSErrors: true });25  await context.route('**/*', route => {26    const url = route.request().url();27    events.emit('request', url);28    route.continue();29  });30  const page = await context.newPage();31  console.log(response.status());32  await browser.close();33})();34events.on('request', (url) => {35  console.log(url);36});37const { chromium } = require('playwright');38const { EventEmitter } = require('events');39const events = new EventEmitter();40(async () => {41  const browser = await chromium.launch({ headless: false });42  const context = await browser.newContext({ ignoreHTTPSErrors: true });43  await context.route('**/*', route => {Using AI Code Generation
1const { chromium } = require('playwright');2const { OnChannelRedirect } = require('playwright/lib/internal/chromium/crNetworkManager');3const { helper } = require('playwright/lib/helper');4(async () => {5  const browser = await chromium.launch();6  const context = await browser.newContext();7  const page = await context.newPage();8  const client = await page.context().newCDPSession(page);9  await client.send('Network.enable');10  client.on('Network.requestWillBeSent', (params) => {11    console.log('requestWillBeSent: ' + params.request.url);12  });13  client.on('Network.responseReceived', (params) => {14    console.log('responseReceived: ' + params.response.url);15  });16  client.on('Network.loadingFinished', (params) => {17    console.log('loadingFinished: ' + params.requestId);18  });19  client.on('Network.loadingFailed', (params) => {20    console.log('loadingFailed: ' + params.requestId);21  });22  OnChannelRedirect.call(client, (event) => {23    console.log('OnChannelRedirect: ' + event.redirectUrl);24  });25  await browser.close();26})();27const { helper } = require('../helper');28const { assert } = require('../helper');29const { Events } = require('../events');30const { Protocol } = require('./protocol');31const { NetworkManager } = require('../networkManager');32const { SecurityDetails } = require('../securityDetails');33const { ResourceTiming } = require('../resourceTiming');34const { Request } = require('../request');35const { Response } = require('../response');36const { HeadersArray } = require('../headersArray');37const { assertMaxArguments } = require('../helper');38const { SdkObject } = require('../instrumentation');39const { SdkObjectWithId } = require('../instrumentation');40class CrNetworkManager extends NetworkManager {41   * @param {!Puppeteer.CDPSession} client42   * @param {!Puppeteer.FrameManager} frameManager43   * @param {!Puppeteer.NetworkManager} networkManager44  constructor(client, frameManager, networkManager) {45    super(client, frameManager, networkManager);46    /** @type {!MapUsing AI Code Generation
1const {chromium} = require('playwright');2const {OnChannelRedirect} = require('playwright/lib/utils/protocol-profiler');3(async () => {4    const browser = await chromium.launch();5    const context = await browser.newContext();6    const page = await context.newPage();7    const client = await page.context().newCDPSession(page);8    const profiler = new OnChannelRedirect(client);9    await profiler.start();10    await profiler.stop();11    const data = profiler.getEvents();12    console.log(data);13    await browser.close();14})();Using AI Code Generation
1const { chromium } = require('playwright');2const { HttpServer } = require('playwright-core/lib/server/httpServer');3const { HttpsServer } = require('playwright-core/lib/server/httpsServer');4const { WebSocketServer } = require('playwright-core/lib/server/webSocketServer');5const { WebSocketTransport } = require('playwright-core/lib/server/webSocketTransport');6const { BrowserContext } = require('playwright-core/lib/server/browserContext');7const { Browser } = require('playwright-core/lib/server/browser');8const { BrowserServer } = require('playwright-core/lib/server/browserServer');9const { BrowserType } = require('playwright-core/lib/server/browserType');10const { BrowserContextChannel } = require('playwright-core/lib/server/browserContextChannel');11const { BrowserTypeChannel } = require('playwright-core/lib/server/browserTypeChannel');12const { BrowserChannel } = require('playwright-core/lib/server/browserChannel');13const { BrowserServerChannel } = require('playwright-core/lib/server/browserServerChannel');14const { Playwright } = require('playwright-core/lib/server/playwright');15const { PlaywrightChannel } = require('playwright-core/lib/server/playwrightChannel');16const { createGuid } = require('playwright-core/lib/utils/utils');17const { assert } = require('playwright-core/lib/utils/utils');18const { BrowserContextBase } = require('playwright-core/lib/server/browserContextBase');19const { BrowserBase } = require('playwright-core/lib/server/browserBase');20const { BrowserTypeBase } = require('playwright-core/lib/server/browserTypeBase');21const { BrowserServerBase } = require('playwright-core/lib/server/browserServerBase');22const { PlaywrightBase } = require('playwright-core/lib/server/playwrightBase');23const { BrowserContextDispatcher } = require('playwright-core/lib/server/browserContextDispatcher');24const { BrowserDispatcher } = require('playwright-core/lib/server/browserDispatcher');25const { BrowserTypeDispatcher } = require('playwright-core/lib/server/browserTypeDispatcher');26const { BrowserServerDispatcher } = require('playwright-core/lib/server/browserServerDispatcher');27const { PlaywrightDispatcher } = require('playwright-core/lib/server/playwrightDispatcher');28const { BrowserContextOwner } = require('playwright-core/lib/server/browserContextOwner');29const { BrowserOwner } = require('playwright-core/lib/server/browserOwner');Using AI Code Generation
1const { chromium } = require('playwright');2const browser = await chromium.launch();3const page = await browser.newPage();4await page.route('**', route => {5  if (route.request().url().endsWith('test.mp3')) {6    route.fulfill({7      body: Buffer.from('test'),8      headers: {9      },10    });11  } else {12    route.continue();13  }14});15await page.close();16await browser.close();17const { chromium } = require('playwright');18const browser = await chromium.launch();19const page = await browser.newPage();20await page.route('**', route => {21  if (route.request().url().endsWith('test.mp3')) {22    route.fulfill({23      body: Buffer.from('test'),24      headers: {25      },26    });27  } else {28    route.continue();29  }30});31await page.close();32await browser.close();33const { chromium } = require('playwright');34const browser = await chromium.launch();35const page = await browser.newPage();36await page.route('**', route => {37  if (route.request().url().endsWith('test.mp3')) {38    route.fulfill({39      body: Buffer.from('test'),40      headers: {41      },42    });43  } else {44    route.continue();45  }46});47await page.close();48await browser.close();49const { chromium } = require('playwright');50const browser = await chromium.launch();51const page = await browser.newPage();52await page.route('**', route => {53  if (route.request().url().endsWith('test.mp3')) {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!!
