Best JavaScript code snippet using playwright-internal
browserContext.js
Source:browserContext.js  
...372    options.recordVideo.size.height &= ~1;373  }374  if (options.proxy) {375    if (!browserOptions.proxy && browserOptions.isChromium && os.platform() === 'win32') throw new Error(`Browser needs to be launched with the global proxy. If all contexts override the proxy, global proxy will be never used and can be any string, for example "launch({ proxy: { server: 'http://per-context' } })"`);376    options.proxy = normalizeProxySettings(options.proxy);377  }378  if ((0, _utils.debugMode)() === 'inspector') options.bypassCSP = true;379  verifyGeolocation(options.geolocation);380}381function verifyGeolocation(geolocation) {382  if (!geolocation) return;383  geolocation.accuracy = geolocation.accuracy || 0;384  const {385    longitude,386    latitude,387    accuracy388  } = geolocation;389  if (longitude < -180 || longitude > 180) throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);390  if (latitude < -90 || latitude > 90) throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);391  if (accuracy < 0) throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);392}393function normalizeProxySettings(proxy) {394  let {395    server,396    bypass397  } = proxy;398  let url;399  try {400    // new URL('127.0.0.1:8080') throws401    // new URL('localhost:8080') fails to parse host or protocol402    // In both of these cases, we need to try re-parse URL with `http://` prefix.403    url = new URL(server);404    if (!url.host || !url.protocol) url = new URL('http://' + server);405  } catch (e) {406    url = new URL('http://' + server);407  }...browserType.js
Source:browserType.js  
1"use strict";2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports.BrowserType = void 0;6var _fs = _interopRequireDefault(require("fs"));7var os = _interopRequireWildcard(require("os"));8var _path = _interopRequireDefault(require("path"));9var _browserContext = require("./browserContext");10var _registry = require("../utils/registry");11var _transport = require("./transport");12var _processLauncher = require("../utils/processLauncher");13var _pipeTransport = require("./pipeTransport");14var _progress = require("./progress");15var _timeoutSettings = require("../utils/timeoutSettings");16var _utils = require("../utils/utils");17var _helper = require("./helper");18var _debugLogger = require("../utils/debugLogger");19var _instrumentation = require("./instrumentation");20function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }21function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }22function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }23/**24 * Copyright (c) Microsoft Corporation.25 *26 * Licensed under the Apache License, Version 2.0 (the "License");27 * you may not use this file except in compliance with the License.28 * You may obtain a copy of the License at29 *30 * http://www.apache.org/licenses/LICENSE-2.031 *32 * Unless required by applicable law or agreed to in writing, software33 * distributed under the License is distributed on an "AS IS" BASIS,34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.35 * See the License for the specific language governing permissions and36 * limitations under the License.37 */38class BrowserType extends _instrumentation.SdkObject {39  constructor(browserName, playwrightOptions) {40    super(playwrightOptions.rootSdkObject, 'browser-type');41    this._name = void 0;42    this._playwrightOptions = void 0;43    this.attribution.browserType = this;44    this._playwrightOptions = playwrightOptions;45    this._name = browserName;46  }47  executablePath() {48    return _registry.registry.findExecutable(this._name).executablePath(this._playwrightOptions.sdkLanguage) || '';49  }50  name() {51    return this._name;52  }53  async launch(metadata, options, protocolLogger) {54    options = this._validateLaunchOptions(options);55    const controller = new _progress.ProgressController(metadata, this);56    controller.setLogName('browser');57    const browser = await controller.run(progress => {58      const seleniumHubUrl = options.__testHookSeleniumRemoteURL || process.env.SELENIUM_REMOTE_URL;59      if (seleniumHubUrl) return this._launchWithSeleniumHub(progress, seleniumHubUrl, options);60      return this._innerLaunchWithRetries(progress, options, undefined, _helper.helper.debugProtocolLogger(protocolLogger)).catch(e => {61        throw this._rewriteStartupError(e);62      });63    }, _timeoutSettings.TimeoutSettings.timeout(options));64    return browser;65  }66  async launchPersistentContext(metadata, userDataDir, options) {67    options = this._validateLaunchOptions(options);68    const controller = new _progress.ProgressController(metadata, this);69    const persistent = options;70    controller.setLogName('browser');71    const browser = await controller.run(progress => {72      return this._innerLaunchWithRetries(progress, options, persistent, _helper.helper.debugProtocolLogger(), userDataDir).catch(e => {73        throw this._rewriteStartupError(e);74      });75    }, _timeoutSettings.TimeoutSettings.timeout(options));76    return browser._defaultContext;77  }78  async _innerLaunchWithRetries(progress, options, persistent, protocolLogger, userDataDir) {79    try {80      return this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);81    } catch (error) {82      // @see https://github.com/microsoft/playwright/issues/521483      const errorMessage = typeof error === 'object' && typeof error.message === 'string' ? error.message : '';84      if (errorMessage.includes('Inconsistency detected by ld.so')) {85        progress.log(`<restarting browser due to hitting race condition in glibc>`);86        return this._innerLaunch(progress, options, persistent, protocolLogger, userDataDir);87      }88      throw error;89    }90  }91  async _innerLaunch(progress, options, persistent, protocolLogger, userDataDir) {92    options.proxy = options.proxy ? (0, _browserContext.normalizeProxySettings)(options.proxy) : undefined;93    const browserLogsCollector = new _debugLogger.RecentLogsCollector();94    const {95      browserProcess,96      artifactsDir,97      transport98    } = await this._launchProcess(progress, options, !!persistent, browserLogsCollector, userDataDir);99    if (options.__testHookBeforeCreateBrowser) await options.__testHookBeforeCreateBrowser();100    const browserOptions = { ...this._playwrightOptions,101      name: this._name,102      isChromium: this._name === 'chromium',103      channel: options.channel,104      slowMo: options.slowMo,105      persistent,106      headful: !options.headless,107      artifactsDir,108      downloadsPath: options.downloadsPath || artifactsDir,109      tracesDir: options.tracesDir || artifactsDir,110      browserProcess,111      customExecutablePath: options.executablePath,112      proxy: options.proxy,113      protocolLogger,114      browserLogsCollector,115      wsEndpoint: options.useWebSocket ? transport.wsEndpoint : undefined116    };117    if (persistent) (0, _browserContext.validateBrowserContextOptions)(persistent, browserOptions);118    copyTestHooks(options, browserOptions);119    const browser = await this._connectToTransport(transport, browserOptions); // We assume no control when using custom arguments, and do not prepare the default context in that case.120    if (persistent && !options.ignoreAllDefaultArgs) await browser._defaultContext._loadDefaultContext(progress);121    return browser;122  }123  async _launchProcess(progress, options, isPersistent, browserLogsCollector, userDataDir) {124    var _options$args;125    const {126      ignoreDefaultArgs,127      ignoreAllDefaultArgs,128      args = [],129      executablePath = null,130      handleSIGINT = true,131      handleSIGTERM = true,132      handleSIGHUP = true133    } = options;134    const env = options.env ? (0, _processLauncher.envArrayToObject)(options.env) : process.env;135    const tempDirectories = [];136    if (options.downloadsPath) await _fs.default.promises.mkdir(options.downloadsPath, {137      recursive: true138    });139    if (options.tracesDir) await _fs.default.promises.mkdir(options.tracesDir, {140      recursive: true141    });142    const artifactsDir = await _fs.default.promises.mkdtemp(_path.default.join(os.tmpdir(), 'playwright-artifacts-'));143    tempDirectories.push(artifactsDir);144    if (userDataDir) {145      // Firefox bails if the profile directory does not exist, Chrome creates it. We ensure consistent behavior here.146      if (!(await (0, _utils.existsAsync)(userDataDir))) await _fs.default.promises.mkdir(userDataDir, {147        recursive: true,148        mode: 0o700149      });150    } else {151      userDataDir = await _fs.default.promises.mkdtemp(_path.default.join(os.tmpdir(), `playwright_${this._name}dev_profile-`));152      tempDirectories.push(userDataDir);153    }154    const browserArguments = [];155    if (ignoreAllDefaultArgs) browserArguments.push(...args);else if (ignoreDefaultArgs) browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));else browserArguments.push(...this._defaultArgs(options, isPersistent, userDataDir));156    let executable;157    if (executablePath) {158      if (!(await (0, _utils.existsAsync)(executablePath))) throw new Error(`Failed to launch ${this._name} because executable doesn't exist at ${executablePath}`);159      executable = executablePath;160    } else {161      const registryExecutable = _registry.registry.findExecutable(options.channel || this._name);162      if (!registryExecutable || registryExecutable.browserName !== this._name) throw new Error(`Unsupported ${this._name} channel "${options.channel}"`);163      executable = registryExecutable.executablePathOrDie(this._playwrightOptions.sdkLanguage);164      await registryExecutable.validateHostRequirements(this._playwrightOptions.sdkLanguage);165    }166    let wsEndpointCallback;167    const shouldWaitForWSListening = options.useWebSocket || ((_options$args = options.args) === null || _options$args === void 0 ? void 0 : _options$args.some(a => a.startsWith('--remote-debugging-port')));168    const waitForWSEndpoint = shouldWaitForWSListening ? new Promise(f => wsEndpointCallback = f) : undefined; // Note: it is important to define these variables before launchProcess, so that we don't get169    // "Cannot access 'browserServer' before initialization" if something went wrong.170    let transport = undefined;171    let browserProcess = undefined;172    const {173      launchedProcess,174      gracefullyClose,175      kill176    } = await (0, _processLauncher.launchProcess)({177      command: executable,178      args: browserArguments,179      env: this._amendEnvironment(env, userDataDir, executable, browserArguments),180      handleSIGINT,181      handleSIGTERM,182      handleSIGHUP,183      log: message => {184        if (wsEndpointCallback) {185          const match = message.match(/DevTools listening on (.*)/);186          if (match) wsEndpointCallback(match[1]);187        }188        progress.log(message);189        browserLogsCollector.log(message);190      },191      stdio: 'pipe',192      tempDirectories,193      attemptToGracefullyClose: async () => {194        if (options.__testHookGracefullyClose) await options.__testHookGracefullyClose(); // We try to gracefully close to prevent crash reporting and core dumps.195        // Note that it's fine to reuse the pipe transport, since196        // our connection ignores kBrowserCloseMessageId.197        this._attemptToGracefullyCloseBrowser(transport);198      },199      onExit: (exitCode, signal) => {200        if (browserProcess && browserProcess.onclose) browserProcess.onclose(exitCode, signal);201      }202    });203    async function closeOrKill(timeout) {204      let timer;205      try {206        await Promise.race([gracefullyClose(), new Promise((resolve, reject) => timer = setTimeout(reject, timeout))]);207      } catch (ignored) {208        await kill().catch(ignored => {}); // Make sure to await actual process exit.209      } finally {210        clearTimeout(timer);211      }212    }213    browserProcess = {214      onclose: undefined,215      process: launchedProcess,216      close: () => closeOrKill(options.__testHookBrowserCloseTimeout || _timeoutSettings.DEFAULT_TIMEOUT),217      kill218    };219    progress.cleanupWhenAborted(() => closeOrKill(progress.timeUntilDeadline()));220    let wsEndpoint;221    if (shouldWaitForWSListening) wsEndpoint = await waitForWSEndpoint;222    if (options.useWebSocket) {223      transport = await _transport.WebSocketTransport.connect(progress, wsEndpoint);224    } else {225      const stdio = launchedProcess.stdio;226      transport = new _pipeTransport.PipeTransport(stdio[3], stdio[4]);227    }228    return {229      browserProcess,230      artifactsDir,231      transport232    };233  }234  async connectOverCDP(metadata, endpointURL, options, timeout) {235    throw new Error('CDP connections are only supported by Chromium');236  }237  async _launchWithSeleniumHub(progress, hubUrl, options) {238    throw new Error('Connecting to SELENIUM_REMOTE_URL is only supported by Chromium');239  }240  _validateLaunchOptions(options) {241    const {242      devtools = false243    } = options;244    let {245      headless = !devtools,246      downloadsPath,247      proxy248    } = options;249    if ((0, _utils.debugMode)()) headless = false;250    if (downloadsPath && !_path.default.isAbsolute(downloadsPath)) downloadsPath = _path.default.join(process.cwd(), downloadsPath);251    if (this._playwrightOptions.socksProxyPort) proxy = {252      server: `socks5://127.0.0.1:${this._playwrightOptions.socksProxyPort}`253    };254    return { ...options,255      devtools,256      headless,257      downloadsPath,258      proxy259    };260  }261}262exports.BrowserType = BrowserType;263function copyTestHooks(from, to) {264  for (const [key, value] of Object.entries(from)) {265    if (key.startsWith('__testHook')) to[key] = value;266  }...Using AI Code Generation
1const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');2const { parseProxySettings } = require('playwright-core/lib/utils/utils');3console.log(normalizeProxySettings(proxySettings));4const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');5const { parseProxySettings } = require('playwright-core/lib/utils/utils');6console.log(normalizeProxySettings(proxySettings));7const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');8const { parseProxySettings } = require('playwright-core/lib/utils/utils');9console.log(normalizeProxySettings(proxySettings));10const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');11const { parseProxySettings } = require('playwright-core/lib/utils/utils');12console.log(normalizeProxySettings(proxySettings));13const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');14const { parseProxySettings } = require('playwright-core/lib/utils/utils');15console.log(normalizeProxySettings(proxySettings));16const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');17const { parseProxySettings } = require('playwright-core/lib/utils/utils');18console.log(normalizeProxySettings(proxySettings));19const { normalizeProxySettings } = require('playwright-core/lib/server/proxy');20const { parseProxySettings } = require('playwright-core/lib/utils/utils');21console.log(normalizeProxySettings(proxySettings));Using AI Code Generation
1const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');2const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');3const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');4const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');5const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');6const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');7const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');8const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');9const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');10const { normalizeProxySettings } = require('playwright/lib/utils/utils.js');Using AI Code Generation
1const internal = require('playwright/lib/server/supplements/utils/internal');2const settings = {3};4const normalizedSettings = internal.normalizeProxySettings(settings);5console.log(normalizedSettings);6const internal = require('playwright/lib/server/supplements/utils/internal');7const settings = {8};9const normalizedSettings = internal.normalizeProxySettings(settings);10console.log(normalizedSettings);11const internal = require('playwright/lib/server/supplements/utils/internal');12const settings = {13};14const normalizedSettings = internal.normalizeProxySettings(settings);15console.log(normalizedSettings);16In the above code, we have imported the internal module of Playwright and called the normalizeProxySettings method onLambdaTest’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!!
