Best JavaScript code snippet using playwright-internal
recorderApp.js
Source:recorderApp.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.RecorderApp = void 0;6var _fs = _interopRequireDefault(require("fs"));7var _path = _interopRequireDefault(require("path"));8var _progress = require("../../progress");9var _events = require("events");10var _instrumentation = require("../../instrumentation");11var _utils = require("../../../utils/utils");12var _crApp = require("../../chromium/crApp");13function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }14/**15 * Copyright (c) Microsoft Corporation.16 *17 * Licensed under the Apache License, Version 2.0 (the "License");18 * you may not use this file except in compliance with the License.19 * You may obtain a copy of the License at20 *21 * http://www.apache.org/licenses/LICENSE-2.022 *23 * Unless required by applicable law or agreed to in writing, software24 * distributed under the License is distributed on an "AS IS" BASIS,25 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26 * See the License for the specific language governing permissions and27 * limitations under the License.28 */29class RecorderApp extends _events.EventEmitter {30 constructor(page, wsEndpoint) {31 super();32 this._page = void 0;33 this.wsEndpoint = void 0;34 this.setMaxListeners(0);35 this._page = page;36 this.wsEndpoint = wsEndpoint;37 }38 async close() {39 await this._page.context().close((0, _instrumentation.internalCallMetadata)());40 }41 async _init() {42 await (0, _crApp.installAppIcon)(this._page);43 await this._page._setServerRequestInterceptor(async route => {44 if (route.request().url().startsWith('https://playwright/')) {45 const uri = route.request().url().substring('https://playwright/'.length);46 const file = require.resolve('../../../web/recorder/' + uri);47 const buffer = await _fs.default.promises.readFile(file);48 await route.fulfill({49 status: 200,50 headers: [{51 name: 'Content-Type',52 value: extensionToMime[_path.default.extname(file)]53 }],54 body: buffer.toString('base64'),55 isBase64: true56 });57 return;58 }59 await route.continue();60 });61 await this._page.exposeBinding('dispatch', false, (_, data) => this.emit('event', data));62 this._page.once('close', () => {63 this.emit('close');64 this._page.context().close((0, _instrumentation.internalCallMetadata)()).catch(e => console.error(e));65 });66 const mainFrame = this._page.mainFrame();67 await mainFrame.goto((0, _instrumentation.internalCallMetadata)(), 'https://playwright/index.html');68 }69 static async open(inspectedContext) {70 const recorderPlaywright = require('../../playwright').createPlaywright(true);71 const args = ['--app=data:text/html,', '--window-size=600,600', '--window-position=1280,10'];72 if (process.env.PWTEST_RECORDER_PORT) args.push(`--remote-debugging-port=${process.env.PWTEST_RECORDER_PORT}`);73 let channel;74 let executablePath;75 if (inspectedContext._browser.options.isChromium) {76 channel = inspectedContext._browser.options.channel;77 if (!channel) executablePath = inspectedContext._browser.options.customExecutablePath;78 }79 const context = await recorderPlaywright.chromium.launchPersistentContext((0, _instrumentation.internalCallMetadata)(), '', {80 channel,81 executablePath,82 sdkLanguage: inspectedContext._options.sdkLanguage,83 args,84 noDefaultViewport: true,85 headless: !!process.env.PWTEST_CLI_HEADLESS || (0, _utils.isUnderTest)() && !inspectedContext._browser.options.headful,86 useWebSocket: !!process.env.PWTEST_RECORDER_PORT87 });88 const controller = new _progress.ProgressController((0, _instrumentation.internalCallMetadata)(), context._browser);89 await controller.run(async progress => {90 await context._browser._defaultContext._loadDefaultContextAsIs(progress);91 });92 const [page] = context.pages();93 const result = new RecorderApp(page, context._browser.options.wsEndpoint);94 await result._init();95 return result;96 }97 async setMode(mode) {98 await this._page.mainFrame().evaluateExpression((mode => {99 window.playwrightSetMode(mode);100 }).toString(), true, mode, 'main').catch(() => {});101 }102 async setFile(file) {103 await this._page.mainFrame().evaluateExpression((file => {104 window.playwrightSetFile(file);105 }).toString(), true, file, 'main').catch(() => {});106 }107 async setPaused(paused) {108 await this._page.mainFrame().evaluateExpression((paused => {109 window.playwrightSetPaused(paused);110 }).toString(), true, paused, 'main').catch(() => {});111 }112 async setSources(sources) {113 await this._page.mainFrame().evaluateExpression((sources => {114 window.playwrightSetSources(sources);115 }).toString(), true, sources, 'main').catch(() => {}); // Testing harness for runCLI mode.116 {117 if (process.env.PWTEST_CLI_EXIT && sources.length) {118 process.stdout.write('\n-------------8<-------------\n');119 process.stdout.write(sources[0].text);120 process.stdout.write('\n-------------8<-------------\n');121 }122 }123 }124 async setSelector(selector, focus) {125 await this._page.mainFrame().evaluateExpression((arg => {126 window.playwrightSetSelector(arg.selector, arg.focus);127 }).toString(), true, {128 selector,129 focus130 }, 'main').catch(() => {});131 }132 async updateCallLogs(callLogs) {133 await this._page.mainFrame().evaluateExpression((callLogs => {134 window.playwrightUpdateLogs(callLogs);135 }).toString(), true, callLogs, 'main').catch(() => {});136 }137 async bringToFront() {138 await this._page.bringToFront();139 }140}141exports.RecorderApp = RecorderApp;142const extensionToMime = {143 '.css': 'text/css',144 '.html': 'text/html',145 '.jpeg': 'image/jpeg',146 '.js': 'application/javascript',147 '.png': 'image/png',148 '.ttf': 'font/ttf',149 '.svg': 'image/svg+xml',150 '.webp': 'image/webp',151 '.woff': 'font/woff',152 '.woff2': 'font/woff2'...
MobileTicket.js
Source:MobileTicket.js
1/**2 * MobileTicket component3 * @flow4 */5import React, {Component} from 'react';6import {Linking, Modal, Platform, ScrollView, StyleSheet, Text, View} from 'react-native';7import Icon from 'react-native-vector-icons/Entypo';8import FoundationIcon from 'react-native-vector-icons/Foundation';9import colors from '../colors';10const styles = StyleSheet.create({11 container: {12 flex: 1,13 marginTop: 20,14 padding: 15,15 },16 childContainer: {17 justifyContent: 'center',18 },19 header: {20 color: colors.brandColor,21 fontSize: 30,22 marginBottom: 15,23 marginTop: 30,24 },25 bigCenteredText: {26 fontSize: 22,27 textAlign: 'center',28 },29 text: {30 color: 'black',31 textAlign: 'center',32 },33 button: {34 alignItems: 'center',35 height: 50,36 justifyContent: 'center',37 width: '90%',38 },39 buttonText: {40 color: 'white',41 fontWeight: '600',42 textAlign: 'center',43 },44 modalWrapper: {45 alignItems: 'center',46 flex: 1,47 justifyContent: 'center',48 },49 wrapper: {50 marginTop: 20,51 },52});53class MobileTicket extends Component { // eslint-disable-line react/prefer-stateless-function54 state = {55 showModal: false,56 }57 closeModal = () => this.setState({showModal: false});58 openStore = () => {59 if (Platform.OS === 'ios') {60 Linking.openURL('https://itunes.apple.com/fi/app/hsl-mobiililippu/id1078566902').catch(e => console.log(e));61 } else {62 Linking.openURL('https://play.google.com/store/apps/details?id=com.hsl.mobiililippu').catch(e => console.log(e));63 }64 }65 maybeOpenMobileTicket = () => {66 Linking.canOpenURL('com.hsl.mobiililippu:?tt=1111')67 .then((isInstalled) => {68 if (isInstalled) {69 Linking.openURL('com.hsl.mobiililippu:?tt=1111').catch(e => console.log(e));70 } else {71 this.setState({showModal: true});72 }73 });74 }75 render() {76 const installAppIcon = Platform.OS === 'ios' ? 'app-store' : 'google-play';77 const modal = this.state.showModal ?78 (79 <Modal80 animationType="slide"81 transparent={false}82 visible83 onRequestClose={this.closeModal}84 >85 <View style={styles.modalWrapper}>86 <Text style={styles.bigCenteredText}>87 HSL Mobiililippu ei ole asennettuna puhelimeesi.88 </Text>89 <View style={styles.wrapper}>90 <Icon.Button91 name={installAppIcon}92 style={styles.button}93 backgroundColor={colors.brandColor}94 borderRadius={10}95 onPress={this.openStore}96 >97 <Text style={styles.buttonText}>98 Asenna sovellus99 </Text>100 </Icon.Button>101 </View>102 <View style={styles.wrapper}>103 <Icon.Button name="cross" style={styles.button} backgroundColor={colors.brandColor} borderRadius={10} onPress={this.closeModal}>104 <Text style={styles.buttonText}>Sulje</Text>105 </Icon.Button>106 </View>107 </View>108 </Modal>109 ) : null;110 return (111 <ScrollView style={styles.container} contentContainerStyle={styles.childContainer}>112 {modal}113 <Text style={[styles.text, styles.header, {marginTop: Platform.OS === 'ios' ? 60 : 40}]}>114 Osta matkalippu suoraan puhelimeesi115 </Text>116 <Text style={styles.text}>Liput kelpaavat kaikkiin HSL:n kulkuvälineisiin</Text>117 <Text style={styles.text}>118 Tunnistautumalla saat lippuja yhtä edulliseen119 hintaan kuin matkakortilla ostettaessa120 </Text>121 <View style={styles.wrapper}>122 <Icon.Button size={15} name="ticket" style={styles.button} backgroundColor={colors.brandColor} borderRadius={10} onPress={this.maybeOpenMobileTicket}>123 <Text style={styles.buttonText}>Kertalippu</Text>124 </Icon.Button>125 </View>126 <View style={styles.wrapper}>127 <Icon.Button size={15} name="calendar" style={styles.button} backgroundColor={colors.brandColor} borderRadius={10} onPress={this.maybeOpenMobileTicket}>128 <Text style={styles.buttonText}>Vuorokausilippu</Text>129 </Icon.Button>130 </View>131 <View style={styles.wrapper}>132 <FoundationIcon.Button name="calendar" style={styles.button} backgroundColor={colors.brandColor} borderRadius={10} onPress={this.maybeOpenMobileTicket}>133 <Text style={styles.buttonText}>Kausilippu</Text>134 </FoundationIcon.Button>135 </View>136 </ScrollView>137 );138 }139}...
traceViewer.js
Source:traceViewer.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.showTraceViewer = showTraceViewer;6var _path = _interopRequireDefault(require("path"));7var _fs = _interopRequireDefault(require("fs"));8var consoleApiSource = _interopRequireWildcard(require("../../../generated/consoleApiSource"));9var _httpServer = require("../../../utils/httpServer");10var _registry = require("../../../utils/registry");11var _utils = require("../../../utils/utils");12var _crApp = require("../../chromium/crApp");13var _instrumentation = require("../../instrumentation");14var _playwright = require("../../playwright");15var _progress = require("../../progress");16function _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); }17function _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; }18function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }19/**20 * Copyright (c) Microsoft Corporation.21 *22 * Licensed under the Apache License, Version 2.0 (the "License");23 * you may not use this file except in compliance with the License.24 * You may obtain a copy of the License at25 *26 * http://www.apache.org/licenses/LICENSE-2.027 *28 * Unless required by applicable law or agreed to in writing, software29 * distributed under the License is distributed on an "AS IS" BASIS,30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.31 * See the License for the specific language governing permissions and32 * limitations under the License.33 */34async function showTraceViewer(traceUrl, browserName, headless = false, port) {35 if (traceUrl && !traceUrl.startsWith('http://') && !traceUrl.startsWith('https://') && !_fs.default.existsSync(traceUrl)) {36 console.error(`Trace file ${traceUrl} does not exist!`);37 process.exit(1);38 }39 const server = new _httpServer.HttpServer();40 server.routePrefix('/trace', (request, response) => {41 const url = new URL('http://localhost' + request.url);42 const relativePath = url.pathname.slice('/trace'.length);43 if (relativePath.startsWith('/file')) {44 try {45 return server.serveFile(request, response, url.searchParams.get('path'));46 } catch (e) {47 return false;48 }49 }50 const absolutePath = _path.default.join(__dirname, '..', '..', '..', 'webpack', 'traceViewer', ...relativePath.split('/'));51 return server.serveFile(request, response, absolutePath);52 });53 const urlPrefix = await server.start(port);54 const traceViewerPlaywright = (0, _playwright.createPlaywright)('javascript', true);55 const traceViewerBrowser = (0, _utils.isUnderTest)() ? 'chromium' : browserName;56 const args = traceViewerBrowser === 'chromium' ? ['--app=data:text/html,', '--window-size=1280,800', '--test-type='] : [];57 if ((0, _utils.isUnderTest)()) args.push(`--remote-debugging-port=0`);58 const context = await traceViewerPlaywright[traceViewerBrowser].launchPersistentContext((0, _instrumentation.internalCallMetadata)(), '', {59 // TODO: store language in the trace.60 channel: (0, _registry.findChromiumChannel)(traceViewerPlaywright.options.sdkLanguage),61 args,62 noDefaultViewport: true,63 ignoreDefaultArgs: ['--enable-automation'],64 headless,65 useWebSocket: (0, _utils.isUnderTest)()66 });67 const controller = new _progress.ProgressController((0, _instrumentation.internalCallMetadata)(), context._browser);68 await controller.run(async progress => {69 await context._browser._defaultContext._loadDefaultContextAsIs(progress);70 });71 await context.extendInjectedScript(consoleApiSource.source);72 const [page] = context.pages();73 if (traceViewerBrowser === 'chromium') await (0, _crApp.installAppIcon)(page);74 if ((0, _utils.isUnderTest)()) page.on('close', () => context.close((0, _instrumentation.internalCallMetadata)()).catch(() => {}));else page.on('close', () => process.exit());75 await page.mainFrame().goto((0, _instrumentation.internalCallMetadata)(), urlPrefix + `/trace/index.html${traceUrl ? '?trace=' + traceUrl : ''}`);76 return context;...
Instance.js
Source:Instance.js
...10 return ipcRenderer.invoke(`instance.${key}`, this.id, ...args);11 }12 init(icon) {13 this.initNotification();14 this.installAppIcon(icon);15 this.observeTheme();16 }17 initNotification() {18 // override Notification API so it can show the window on click19 window.oldNotification = Notification;20 Settings.onDidChange('notification.legacyType', this.setNotification);21 this.setNotification();22 }23 setNotification() {24 if(Settings.get('notification.legacyType.value')) {25 window.Notification = LegacyNotification;26 } else {27 window.Notification = ServerNotification;28 }29 }30 installAppIcon(icon) {31 const container = document.querySelector('#side header div:first-child');32 const image = new Image();33 container.style.display = 'flex';34 container.style.alignItems = 'center';35 image.src = icon;36 image.title = 'Open Dashboard';37 image.style = `38 display: block;39 margin-left: auto;40 margin-right: 16px;41 width: 30px;42 height: 30px;43 cursor: pointer;44 `;...
app.js
Source:app.js
...25 if (show_file != null) {26 show_file.addEventListener('click', installAppIcon);27 }28}29function installAppIcon() {30 console.log(deferredPrompt + " prom")31 if (deferredPrompt) {32 deferredPrompt.prompt();33 deferredPrompt.userChoice.then(function (choiceResult) {34 console.log(choiceResult.outcome);35 if (choiceResult.outcome === 'dismissed') {36 console.log('User cancelled installation');37 } else {38 console.log('User added to home screen');39 }40 });41 deferredPrompt = null;42 }43}
crApp.js
Source:crApp.js
...19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.20 * See the License for the specific language governing permissions and21 * limitations under the License.22 */23async function installAppIcon(page) {24 const icon = await _fs.default.promises.readFile(require.resolve('./appIcon.png'));25 const crPage = page._delegate;26 await crPage._mainFrameSession._client.send('Browser.setDockTile', {27 image: icon.toString('base64')28 });...
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 browser.close();8})();9import { chromium } from 'playwright';10declare module 'playwright' {11 interface BrowserContext {12 installAppIcon: (icon: string) => Promise<void>;13 }14}15(async() => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 await page.screenshot({ path: 'google.png' });20 await browser.close();21})();22import { chromium } from 'playwright';23declare module 'playwright' {24 interface BrowserContext {25 installAppIcon(icon: string): Promise<void>;26 }27}28async function main() {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 await page.screenshot({ path: 'google.png' });33 await browser.close();34}35main();36import { chromium } from 'playwright';37declare module 'playwright' {38 interface BrowserContext {39 installAppIcon(icon: string): Promise<void>;40 }41}42async function main() {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.screenshot({ path: 'google.png' });47 await browser.close();48}49main();50import { chromium } from 'playwright';51declare module 'playwright' {
Using AI Code Generation
1const { installAppIcon } = require('playwright/lib/server/chromium/crBrowser');2const { chromium } = require('playwright');3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6const { launchServer } = require('playwright/lib/server/server');7const server = await launchServer({
Using AI Code Generation
1const {chromium} = require('playwright');2const { installAppIcon } = require('playwright/lib/install-app-icon');3const browser = await chromium.launch();4const context = await browser.newContext();5await browser.close();6const {chromium} = require('playwright');7const browser = await chromium.launch();8const context = await browser.newContext();9await context.addInitScript(() => {10 globalThis.installAppIcon = async (url) => {11 };12});13await browser.close();14const {chromium} = require('playwright');15const browser = await chromium.launch();16const context = await browser.newContext();17await context.addInitScript(() => {18 globalThis.installAppIcon = async (url) => {19 };20});21await browser.close();22const {chromium} = require('playwright');23const browser = await chromium.launch();24const context = await browser.newContext();25await context.addInitScript(() => {26 globalThis.installAppIcon = async (url) => {27 };28});29await browser.close();30const {chromium} = require('playwright');31const browser = await chromium.launch();32const context = await browser.newContext();33await context.addInitScript(() => {34 globalThis.installAppIcon = async (url) => {35 };36});37await browser.close();38const {chromium} = require('playwright');39const browser = await chromium.launch();40const context = await browser.newContext();41await context.addInitScript(() => {42 globalThis.installAppIcon = async (url) => {43 };44});45await browser.close();46const {chromium} = require('playwright');47const browser = await chromium.launch();48const context = await browser.newContext();49await context.addInitScript(() => {50 globalThis.installAppIcon = async (url) => {51 };52});53await browser.close();
Using AI Code Generation
1const { installAppIcon } = require('@playwright/test/lib/internal/inspector/installAppIcon');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await installAppIcon(page);8 await browser.close();9})();
Using AI Code Generation
1const { installAppIcon } = require(‘playwright’);2(async () => {3})();4const { uninstallAppIcon } = require(‘playwright’);5(async () => {6})();7const { launchPersistentContext } = require(‘playwright’);8(async () => {9})();10const { launchServer } = require(‘playwright’);11(async () => {12})();13const { launchServer } = require(‘playwright’);14(async () => {15})();16const { launchServer } = require(‘playwright’);17(async () => {18})();19const { launchServer } = require(‘playwright’);20(async () => {21})();22const { launchServer } = require(‘playwright’);23(async () => {24})();25const { launchServer } = require(‘playwright’);26(async () => {27})();28const { launchServer } = require(‘playwright’);29(async () => {30})();31const { launchServer } = require(‘playwright’);32(async () => {33})();34const { launchServer } = require(‘playwright’);35(async () => {
Using AI Code Generation
1const { installAppIcon } = require('playwright');2const { devices } = require('playwright');3const iPhone = devices['iPhone 11 Pro'];4const context = await browser.newContext({5});6const page = await context.newPage();7const { uninstallAppIcon } = require('playwright');8const { devices } = require('playwright');9const iPhone = devices['iPhone 11 Pro'];10const context = await browser.newContext({11});12const page = await context.newPage();13const { launchPersistentContext } = require('playwright');14const { devices } = require('playwright');15const iPhone = devices['iPhone 11 Pro'];16const context = await launchPersistentContext('data-dir', {17});18const page = await context.newPage();19const { launchServer } = require('playwright');20const server = await launchServer({21 launchOptions: {},22 env: {},23});24await server.close();25const { launch } = require('playwright');26const browser = await launch({27 env: {28 },
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!!