How to use _onTargetCreated method in Puppeteer

Best JavaScript code snippet using puppeteer

scratch3_sound.js

Source:scratch3_sound.js Github

copy

Full Screen

1const MathUtil = require('../util/math-util');2const Cast = require('../util/cast');3const Clone = require('../util/clone');4class Scratch3SoundBlocks {5 constructor (runtime) {6 /**7 * The runtime instantiating this block package.8 * @type {Runtime}9 */10 this.runtime = runtime;11 // Clear sound effects on green flag and stop button events.12 this._clearEffectsForAllTargets = this._clearEffectsForAllTargets.bind(this);13 if (this.runtime) {14 this.runtime.on('PROJECT_STOP_ALL', this._clearEffectsForAllTargets);15 this.runtime.on('PROJECT_START', this._clearEffectsForAllTargets);16 }17 this._onTargetCreated = this._onTargetCreated.bind(this);18 if (this.runtime) {19 runtime.on('targetWasCreated', this._onTargetCreated);20 }21 }22 /**23 * The key to load & store a target's sound-related state.24 * @type {string}25 */26 static get STATE_KEY () {27 return 'Scratch.sound';28 }29 /**30 * The default sound-related state, to be used when a target has no existing sound state.31 * @type {SoundState}32 */33 static get DEFAULT_SOUND_STATE () {34 return {35 effects: {36 pitch: 0,37 pan: 038 }39 };40 }41 /**42 * The minimum and maximum MIDI note numbers, for clamping the input to play note.43 * @type {{min: number, max: number}}44 */45 static get MIDI_NOTE_RANGE () {46 return {min: 36, max: 96}; // C2 to C747 }48 /**49 * The minimum and maximum beat values, for clamping the duration of play note, play drum and rest.50 * 100 beats at the default tempo of 60bpm is 100 seconds.51 * @type {{min: number, max: number}}52 */53 static get BEAT_RANGE () {54 return {min: 0, max: 100};55 }56 /** The minimum and maximum tempo values, in bpm.57 * @type {{min: number, max: number}}58 */59 static get TEMPO_RANGE () {60 return {min: 20, max: 500};61 }62 /** The minimum and maximum values for each sound effect.63 * @type {{effect:{min: number, max: number}}}64 */65 static get EFFECT_RANGE () {66 return {67 pitch: {min: -360, max: 360}, // -3 to 3 octaves68 pan: {min: -100, max: 100} // 100% left to 100% right69 };70 }71 /**72 * @param {Target} target - collect sound state for this target.73 * @returns {SoundState} the mutable sound state associated with that target. This will be created if necessary.74 * @private75 */76 _getSoundState (target) {77 let soundState = target.getCustomState(Scratch3SoundBlocks.STATE_KEY);78 if (!soundState) {79 soundState = Clone.simple(Scratch3SoundBlocks.DEFAULT_SOUND_STATE);80 target.setCustomState(Scratch3SoundBlocks.STATE_KEY, soundState);81 target.soundEffects = soundState.effects;82 }83 return soundState;84 }85 /**86 * When a Target is cloned, clone the sound state.87 * @param {Target} newTarget - the newly created target.88 * @param {Target} [sourceTarget] - the target used as a source for the new clone, if any.89 * @listens Runtime#event:targetWasCreated90 * @private91 */92 _onTargetCreated (newTarget, sourceTarget) {93 if (sourceTarget) {94 const soundState = sourceTarget.getCustomState(Scratch3SoundBlocks.STATE_KEY);95 if (soundState && newTarget) {96 newTarget.setCustomState(Scratch3SoundBlocks.STATE_KEY, Clone.simple(soundState));97 this._syncEffectsForTarget(newTarget);98 }99 }100 }101 /**102 * Retrieve the block primitives implemented by this package.103 * @return {object.<string, Function>} Mapping of opcode to Function.104 */105 getPrimitives () {106 return {107 sound_play: this.playSound,108 sound_playuntildone: this.playSoundAndWait,109 sound_stopallsounds: this.stopAllSounds,110 sound_seteffectto: this.setEffect,111 sound_changeeffectby: this.changeEffect,112 sound_cleareffects: this.clearEffects,113 sound_sounds_menu: this.soundsMenu,114 sound_beats_menu: this.beatsMenu,115 sound_effects_menu: this.effectsMenu,116 sound_setvolumeto: this.setVolume,117 sound_changevolumeby: this.changeVolume,118 sound_volume: this.getVolume119 };120 }121 getMonitored () {122 return {123 sound_volume: {124 getId: () => 'volume'125 }126 };127 }128 playSound (args, util) {129 // Don't return the promise, it's the only difference for AndWait130 this.playSoundAndWait(args, util);131 }132 playSoundAndWait (args, util) {133 const index = this._getSoundIndex(args.SOUND_MENU, util);134 if (index >= 0) {135 const {target} = util;136 const {sprite} = target;137 const {soundId} = sprite.sounds[index];138 if (sprite.soundBank) {139 return sprite.soundBank.playSound(target, soundId);140 }141 }142 }143 _getSoundIndex (soundName, util) {144 // if the sprite has no sounds, return -1145 const len = util.target.sprite.sounds.length;146 if (len === 0) {147 return -1;148 }149 // look up by name first150 const index = this.getSoundIndexByName(soundName, util);151 if (index !== -1) {152 return index;153 }154 // then try using the sound name as a 1-indexed index155 const oneIndexedIndex = parseInt(soundName, 10);156 if (!isNaN(oneIndexedIndex)) {157 return MathUtil.wrapClamp(oneIndexedIndex - 1, 0, len - 1);158 }159 // could not be found as a name or converted to index, return -1160 return -1;161 }162 getSoundIndexByName (soundName, util) {163 const sounds = util.target.sprite.sounds;164 for (let i = 0; i < sounds.length; i++) {165 if (sounds[i].name === soundName) {166 return i;167 }168 }169 // if there is no sound by that name, return -1170 return -1;171 }172 stopAllSounds () {173 if (this.runtime.targets === null) return;174 const allTargets = this.runtime.targets;175 for (let i = 0; i < allTargets.length; i++) {176 this._stopAllSoundsForTarget(allTargets[i]);177 }178 }179 _stopAllSoundsForTarget (target) {180 if (target.sprite.soundBank) {181 target.sprite.soundBank.stopAllSounds(target);182 }183 }184 setEffect (args, util) {185 return this._updateEffect(args, util, false);186 }187 changeEffect (args, util) {188 return this._updateEffect(args, util, true);189 }190 _updateEffect (args, util, change) {191 const effect = Cast.toString(args.EFFECT).toLowerCase();192 const value = Cast.toNumber(args.VALUE);193 const soundState = this._getSoundState(util.target);194 if (!soundState.effects.hasOwnProperty(effect)) return;195 if (change) {196 soundState.effects[effect] += value;197 } else {198 soundState.effects[effect] = value;199 }200 const {min, max} = Scratch3SoundBlocks.EFFECT_RANGE[effect];201 soundState.effects[effect] = MathUtil.clamp(soundState.effects[effect], min, max);202 this._syncEffectsForTarget(util.target);203 // Yield until the next tick.204 return Promise.resolve();205 }206 _syncEffectsForTarget (target) {207 if (!target || !target.sprite.soundBank) return;208 target.soundEffects = this._getSoundState(target).effects;209 target.sprite.soundBank.setEffects(target);210 }211 clearEffects (args, util) {212 this._clearEffectsForTarget(util.target);213 }214 _clearEffectsForTarget (target) {215 const soundState = this._getSoundState(target);216 for (const effect in soundState.effects) {217 if (!soundState.effects.hasOwnProperty(effect)) continue;218 soundState.effects[effect] = 0;219 }220 this._syncEffectsForTarget(target);221 }222 _clearEffectsForAllTargets () {223 if (this.runtime.targets === null) return;224 const allTargets = this.runtime.targets;225 for (let i = 0; i < allTargets.length; i++) {226 this._clearEffectsForTarget(allTargets[i]);227 }228 }229 setVolume (args, util) {230 const volume = Cast.toNumber(args.VOLUME);231 return this._updateVolume(volume, util);232 }233 changeVolume (args, util) {234 const volume = Cast.toNumber(args.VOLUME) + util.target.volume;235 return this._updateVolume(volume, util);236 }237 _updateVolume (volume, util) {238 volume = MathUtil.clamp(volume, 0, 100);239 util.target.volume = volume;240 this._syncEffectsForTarget(util.target);241 // Yield until the next tick.242 return Promise.resolve();243 }244 getVolume (args, util) {245 return util.target.volume;246 }247 soundsMenu (args) {248 return args.SOUND_MENU;249 }250 beatsMenu (args) {251 return args.BEATS;252 }253 effectsMenu (args) {254 return args.EFFECT;255 }256}...

Full Screen

Full Screen

Target.jsm

Source:Target.jsm Github

copy

Full Screen

...72 targets.off("target-created", this._onTargetCreated);73 targets.off("target-destroyed", this._onTargetDestroyed);74 }75 for (const target of targets) {76 this._onTargetCreated("target-created", target);77 }78 }79 async createTarget({ browserContextId }) {80 const { targets } = this.session.target;81 const onTarget = targets.once("target-created");82 const tab = TabManager.addTab({ userContextId: browserContextId });83 const target = await onTarget;84 if (tab.linkedBrowser != target.browser) {85 throw new Error(86 "Unexpected tab opened: " + tab.linkedBrowser.currentURI.spec87 );88 }89 return { targetId: target.id };90 }91 closeTarget({ targetId }) {92 const { targets } = this.session.target;93 const target = targets.getById(targetId);94 if (!target) {95 throw new Error(`Unable to find target with id '${targetId}'`);96 }97 TabManager.removeTab(target.tab);98 }99 async activateTarget({ targetId }) {100 const { targets, window } = this.session.target;101 const target = targets.getById(targetId);102 if (!target) {103 throw new Error(`Unable to find target with id '${targetId}'`);104 }105 // Focus the window, and select the corresponding tab106 await WindowManager.focus(window);107 TabManager.selectTab(target.tab);108 }109 attachToTarget({ targetId }) {110 const { targets } = this.session.target;111 const target = targets.getById(targetId);112 if (!target) {113 throw new Error(`Unable to find target with id '${targetId}'`);114 }115 const tabSession = new TabSession(116 this.session.connection,117 target,118 UUIDGen.generateUUID()119 .toString()120 .slice(1, -1)121 );122 this.session.connection.registerSession(tabSession);123 this._emitAttachedToTarget(target, tabSession);124 return {125 sessionId: tabSession.id,126 };127 }128 setAutoAttach() {}129 sendMessageToTarget({ sessionId, message }) {130 const { connection } = this.session;131 connection.sendMessageToTarget(sessionId, message);132 }133 /**134 * Internal methods: the following methods are not part of CDP;135 * note the _ prefix.136 */137 _emitAttachedToTarget(target, tabSession) {138 const targetInfo = this._getTargetInfo(target);139 this.emit("Target.attachedToTarget", {140 targetInfo,141 sessionId: tabSession.id,142 waitingForDebugger: false,143 });144 }145 _getTargetInfo(target) {146 return {147 targetId: target.id,148 type: target.type,149 title: target.title,150 url: target.url,151 // TODO: Correctly determine if target is attached (bug 1680780)152 attached: target.id == this.session.target.id,153 browserContextId: target.browserContextId,154 };155 }156 _onTargetCreated(eventName, target) {157 const targetInfo = this._getTargetInfo(target);158 this.emit("Target.targetCreated", { targetInfo });159 }160 _onTargetDestroyed(eventName, target) {161 this.emit("Target.targetDestroyed", {162 targetId: target.id,163 });164 }...

Full Screen

Full Screen

testExtension.js

Source:testExtension.js Github

copy

Full Screen

1// https://cdn.jsdelivr.net/gh/griffpatch/griffpatch.github.io/testExtension.js2// Forked from https://github.com/griffpatch/griffpatch.github.io/blob/master/testExtension.js3// Original Author https://github.com/griffpatch4const ArgumentType = require('../../extension-support/argument-type');5const BlockType = require('../../extension-support/block-type');6const Clone = require('../../util/clone');7const Cast = require('../../util/cast');8const formatMessage = require('format-message');9const MathUtil = require('../../util/math-util');10const Timer = require('../../util/timer');11/**12 * The instrument and drum sounds, loaded as static assets.13 * @type {object}14 */15/*let assetData = {};16try {17 assetData = require('./manifest');18} catch (e) {19 // Non-webpack environment, don't worry about assets.20}*/21/**22 * Class for the music-related blocks in Scratch 3.023 * @param {Runtime} runtime - the runtime instantiating this block package.24 * @constructor25 */26class Scratch3TestExtension {27 constructor (runtime) {28 /**29 * The runtime instantiating this block package.30 * @type {Runtime}31 */32 this.runtime = runtime;33 debugger;34// this._onTargetCreated = this._onTargetCreated.bind(this);35// this.runtime.on('targetWasCreated', this._onTargetCreated);36/*37 this._playNoteForPicker = this._playNoteForPicker.bind(this);38 this.runtime.on('PLAY_NOTE', this._playNoteForPicker);39 */40 }41 /**42 * The key to load & store a target's music-related state.43 * @type {string}44 */45 static get STATE_KEY () {46 return 'Scratch.Griffpatch';47 }48 /**49 * @returns {object} metadata for this extension and its blocks.50 */51 getInfo () {52 return {53 id: 'griffpatch',54 name: formatMessage({55 id: 'griffpatch.categoryName',56 default: 'Griffpatch',57 description: 'Label for the Griffpatch extension category'58 }),59 menuIconURI: menuIconURI,60 blockIconURI: blockIconURI,61 blocks: [62 {63 opcode: 'doTest',64 blockType: BlockType.COMMAND,65 text: formatMessage({66 id: 'griffpatch.test',67 default: 'test [x], [y]',68 description: 'test this block'69 }),70 arguments: {71 x: {72 type: ArgumentType.NUMBER,73 defaultValue: 1074 },75 y: {76 type: ArgumentType.NUMBER,77 defaultValue: 1078 }79 }80 },81 {82 opcode: 'getTest',83 text: formatMessage({84 id: 'griffpatch.getTest',85 default: 'test',86 description: 'get the test value'87 }),88 blockType: BlockType.REPORTER89 }90 ]91 };92 }93 /**94 * Play a drum sound for some number of beats.95 * @param {object} args - the block arguments.96 * @param {object} util - utility object provided by the runtime.97 * @property {int} DRUM - the number of the drum to play.98 * @property {number} BEATS - the duration in beats of the drum sound.99 */100 doTest (x, y) {101 // this._playDrumForBeats(args.DRUM, args.BEATS, util);102 // if (util.runtime.audioEngine === null) return;103 // if (util.target.sprite.soundBank === null) return;104 debugger;105 }106 /**107 * Get the current tempo.108 * @return {number} - the current tempo, in beats per minute.109 */110 getTest () {111 const stage = this.runtime.getTargetForStage();112 debugger;113/* if (stage) {114 return stage.tempo;115 }*/116 return 9000;117 }118}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page._client.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });6 await page._client.on('Target.attachedToTarget', async ({ sessionId }) => {7 const client = await page.target().createCDPSession();8 await client.send('Runtime.enable');9 await client.send('Runtime.runIfWaitingForDebugger');10 });11})();12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 await page._client.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });17 await page._client.on('Target.attachedToTarget', async ({ sessionId }) => {18 const client = await page.target().createCDPSession();19 await client.send('Runtime.enable');20 await client.send('Runtime.runIfWaitingForDebugger');21 });22})();23### page._client.send(method[, params])24### page._client.on(event, callback)25[MIT](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.evaluateOnNewDocument(() => {6 window._onTargetCreated = (target) => {7 target.page().then((page) => {8 page.on('console', (msg) => {9 for (let i = 0; i < msg.args().length; ++i)10 console.log(`${i}: ${msg.args()[i]}`);11 });12 });13 };14 });15 await page.evaluate(() => {16 const newPagePromise = new Promise((x) => window._onTargetCreated = x);17 return newPagePromise;18 });19 await page.evaluate(() => {20 const newPagePromise = new Promise((x) => window._onTargetCreated = x);21 return newPagePromise;22 });23})();24const puppeteer = require('puppeteer');25(async () => {26 const browser = await puppeteer.launch({headless: false});27 const page = await browser.newPage();28 await page.evaluateOnNewDocument(() => {29 window._onTargetCreated = (target) => {30 target.page().then((page) => {31 page.on('console', (msg) => {32 for (let i = 0; i < msg.args().length; ++i)33 console.log(`${i}: ${msg.args()[i]}`);34 });35 });36 };37 });38 await page.evaluate(() => {39 const newPagePromise = new Promise((x) => window._onTargetCreated = x);40 return newPagePromise;41 });42 await page.evaluate(() => {43 const newPagePromise = new Promise((x) => window._onTargetCreated = x);44 return newPagePromise;45 });46})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.screenshot({path: 'google.png'});6 await browser.close();7})();8const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page())));9const newPage = await newPagePromise;10const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page())));11const newPage = await newPagePromise;12const newPagePromise = new Promise(x => browser.once('targetcreated', target => x(target.page()))

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 await page.setViewport({ width: 1920, height: 1080 });7 const newPage = await targetCreated.page();8 await newPage.waitForSelector('input[name="q"]');9 await newPage.type('input[name="q"]', 'puppeteer');10 await newPage.keyboard.press('Enter');11 await newPage.waitForNavigation();12 await newPage.waitForSelector('h3.LC20lb');13 await newPage.click('h3.LC20lb');14 await newPage.waitForNavigation();15 await newPage.waitForSelector('h1');16 const heading = await newPage.$eval('h1', el => el.textContent);17 console.log(heading);18 await page.close();19 await browser.close();20})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({5 });6 const page = await browser.newPage();7 await page._client.send('Page.setDownloadBehavior', {8 });9 await page.click("input[type='file']");10 await page.waitForSelector('input[type="file"]', {11 });12 const [fileChooser] = await Promise.all([13 page.waitForFileChooser(),14 page.click('input[type="file"]'),15 ]);16 await fileChooser.accept(['./test.pdf']);17 await page.waitFor(5000);18 await browser.close();19})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful