Best JavaScript code snippet using chromy
index.js
Source:index.js
...172 const result = await this.client.Target.getTargets()173 return result.targetInfos.filter(t => t.type === 'page')174 }175 async userAgent (ua) {176 await this._checkStart()177 return await this.client.Network.setUserAgentOverride({'userAgent': ua})178 }179 /**180 * Example:181 * chromy.headers({'X-Requested-By': 'foo'})182 */183 async headers (headers) {184 await this._checkStart()185 return await this.client.Network.setExtraHTTPHeaders({'headers': headers})186 }187 async ignoreCertificateErrors () {188 await this._checkStart()189 await this.client.Security.enable()190 await this.client.Security.setOverrideCertificateErrors({override: true})191 await this.client.Security.certificateError(({eventId}) => {192 this.client.Security.handleCertificateError({193 eventId,194 action: 'continue',195 })196 })197 }198 async console (callback) {199 await this._checkStart()200 this.client.Console.messageAdded((payload) => {201 try {202 const msg = payload.message.text203 const pre = this.messagePrefix204 if (typeof msg !== 'undefined') {205 if (pre === null || msg.substring(0, pre.length + 1) !== pre + ':') {206 callback.apply(this, [msg, payload.message])207 }208 }209 } catch (e) {210 console.warn(e)211 }212 })213 }214 async receiveMessage (callback) {215 await this._checkStart()216 const uuid = uuidV4()217 this.messagePrefix = uuid218 const f = makeSendToChromy(this.messagePrefix)219 this.defineFunction({sendToChromy: f})220 this.client.Console.messageAdded((payload) => {221 try {222 const msg = payload.message.text223 if (msg && msg.substring(0, uuid.length + 1) === uuid + ':') {224 const data = JSON.parse(msg.substring(uuid.length + 1))225 callback.apply(this, [data])226 }227 } catch (e) {228 console.warn(e)229 }230 })231 }232 async goto (url, options) {233 // correct url form.234 url = nodeUrl.format(nodeUrl.parse(url))235 const defaultOptions = {236 waitLoadEvent: true,237 }238 options = Object.assign({}, defaultOptions, options)239 await this._checkStart(url)240 let response = null241 // truck redirects.242 let requestListener = (payload) => {243 if (payload.redirectResponse && payload.redirectResponse.url === url) {244 url = payload.redirectResponse.headers.location245 }246 }247 const requestEventName = 'Network.requestWillBeSent'248 await this.on(requestEventName, requestListener)249 let listener = (payload) => {250 if (payload.response.url === url) {251 response = payload.response252 }253 }254 const eventName = 'Network.responseReceived'255 await this.on(eventName, listener)256 try {257 await this._waitFinish(this.options.gotoTimeout, async () => {258 await this.client.Page.navigate({url: completeUrl(url)})259 if (options.waitLoadEvent) {260 await this.client.Page.loadEventFired()261 }262 })263 } catch (e) {264 if (e instanceof TimeoutError) {265 throw new GotoTimeoutError('goto() timeout')266 } else {267 throw e268 }269 } finally {270 await this.removeListener(eventName, listener)271 await this.removeListener(requestEventName, requestListener)272 }273 return response274 }275 async waitLoadEvent () {276 await this._waitFinish(this.options.loadTimeout, async () => {277 await this.client.Page.loadEventFired()278 })279 }280 async forward () {281 const f = 'window.history.forward()'282 const promise = this.waitLoadEvent()283 await this.client.Runtime.evaluate({expression: f})284 await promise285 }286 async back () {287 const f = 'window.history.back()'288 const promise = this.waitLoadEvent()289 await this.client.Runtime.evaluate({expression: f})290 await promise291 }292 async reload (ignoreCache, scriptToEvaluateOnLoad) {293 await this.client.Page.reload({ignoreCache, scriptToEvaluateOnLoad})294 }295 /**296 * define function297 *298 * @param func {(function|string|Array.<function>|Array.<string>)}299 * @returns {Promise.<void>}300 */301 async defineFunction (def) {302 let funcs = []303 if (Array.isArray(def)) {304 funcs = def305 } else if ((typeof def) === 'object') {306 funcs = this._moduleToFunctionSources(def)307 } else {308 funcs.push(def)309 }310 for (let i = 0; i < funcs.length; i++) {311 let f = funcs[i]312 if ((typeof f) === 'function') {313 f = f.toString()314 }315 await this.client.Runtime.evaluate({expression: f})316 }317 }318 _moduleToFunctionSources (module) {319 const result = []320 for (let funcName in module) {321 let func = module[funcName]322 let src = `function ${funcName} () { return (${func.toString()})(...arguments) }`.trim()323 result.push(src)324 }325 return result326 }327 async mouseMoved (x, y, options = {}) {328 const opts = Object.assign({type: 'mouseMoved', x: x, y: y}, options)329 await this.client.Input.dispatchMouseEvent(opts)330 }331 async mousePressed (x, y, options = {}) {332 const opts = Object.assign({type: 'mousePressed', x: x, y: y, button: 'left'}, options)333 await this.client.Input.dispatchMouseEvent(opts)334 }335 async mouseReleased (x, y, options = {}) {336 const opts = Object.assign({type: 'mouseReleased', x: x, y: y, button: 'left'}, options)337 await this.client.Input.dispatchMouseEvent(opts)338 }339 async tap (x, y, options = {}) {340 const time = Date.now() / 1000341 const opts = Object.assign({x: x, y: y, timestamp: time, button: 'left'}, options)342 await this.client.Input.synthesizeTapGesture(opts)343 }344 async doubleTap (x, y, options = {}) {345 const time = Date.now() / 1000346 const opts = Object.assign({x: x, y: y, timestamp: time, button: 'left', tapCount: 2}, options)347 await this.client.Input.synthesizeTapGesture(opts)348 }349 async setFile (selector, files) {350 let paramFiles = files351 if ((typeof files) === 'string') {352 paramFiles = [files]353 }354 if (paramFiles.length === 0) {355 return356 }357 const {root} = await this.client.DOM.getDocument()358 const {nodeId: fileNodeId} = await this.client.DOM.querySelector({359 nodeId: root.nodeId,360 selector: selector,361 })362 if (!fileNodeId) {363 return364 }365 await this.client.DOM.setFileInputFiles({366 nodeId: fileNodeId,367 files: paramFiles,368 })369 }370 async screenshot (format = 'png', quality = undefined, fromSurface = true) {371 let opts = {372 format: 'png',373 fromSurface: true,374 useDeviceResolution: false,375 }376 if ((typeof format) === 'string') {377 // deprecated arguments style378 const params = {379 format: format,380 quality: quality,381 fromSurface: fromSurface,382 }383 opts = Object.assign({}, opts, params)384 } else if ((typeof format) === 'object') {385 opts = Object.assign({}, opts, format)386 }387 if (['png', 'jpeg'].indexOf(opts.format) === -1) {388 throw new Error('format is invalid.')389 }390 const captureParams = Object.assign({}, opts)391 delete captureParams.useDeviceResolution392 let captureResult = await this.client.Page.captureScreenshot(captureParams)393 let image = Buffer.from(captureResult.data, 'base64')394 if (!opts.useDeviceResolution) {395 const screen = await this._getScreenInfo()396 if (screen.devicePixelRatio !== 1) {397 let promise = new Promise((resolve, reject) => {398 Jimp.read(image, (err, img) => {399 if (err) {400 return reject(err)401 }402 let fmt = opts.format === 'png' ? Jimp.MIME_PNG : Jimp.MIME_JPEG403 let quality = 100404 if (opts.quality) {405 quality = opts.quality406 }407 img.scale(1.0 / screen.devicePixelRatio, Jimp.RESIZE_BEZIER)408 .quality(quality)409 .getBuffer(fmt, (err, buffer) => {410 if (err) {411 reject(err)412 } else {413 resolve(buffer)414 }415 })416 })417 })418 image = await promise419 }420 }421 return image422 }423 /*424 * Limitation:425 * maximum height is 16384px because of chrome's bug from Skia library.426 * https://groups.google.com/a/chromium.org/d/msg/headless-dev/DqaAEXyzvR0/kUTEqNYiDQAJ427 * https://stackoverflow.com/questions/44599858/max-height-of-16-384px-for-headless-chrome-screenshots428 */429 async screenshotDocument (model = 'scroll', format = 'png', quality = undefined, fromSurface = true) {430 let opts = {431 model: 'scroll',432 format: 'png',433 fromSurface: true,434 useDeviceResolution: false,435 }436 if ((typeof model) === 'string') {437 const params = {438 model: model,439 format: format,440 quality: quality,441 fromSurface: fromSurface,442 }443 opts = Object.assign({}, opts, params)444 } else if ((typeof model) === 'object') {445 opts = Object.assign({}, opts, model)446 }447 const emulation = await createFullscreenEmulationManager(this, opts.model, false, opts.useDeviceResolution)448 let result = null449 try {450 await emulation.emulate()451 // device resolution is already emulated by emulation manager, so useDeviceResotion must be set true452 const screenshotParams = Object.assign({}, opts, {useDeviceResolution: true})453 delete screenshotParams.model454 result = await this.screenshot(screenshotParams)455 } finally {456 await emulation.reset()457 // restore emulation mode458 await this._restoreEmulationSetting()459 }460 return result461 }462 async screenshotSelector (selector, format = 'png', quality = undefined, fromSurface = true) {463 let opts = {464 format: 'png',465 fromSurface: true,466 useDeviceResolution: false,467 }468 if ((typeof format) === 'string') {469 const params = {470 format: format,471 quality: quality,472 fromSurface: fromSurface,473 }474 opts = Object.assign({}, opts, params)475 } else if ((typeof format) === 'object') {476 opts = Object.assign({}, opts, format)477 }478 return this._screenshotSelector(selector, opts)479 }480 async _screenshotSelector (selector, opts) {481 const emulation = await createFullscreenEmulationManager(this, 'scroll', true, opts.useDeviceResolution)482 let buffer = null483 try {484 await emulation.emulate()485 await this.scrollTo(0, 0)486 let rect = await this.getBoundingClientRect(selector)487 if (!rect || rect.width === 0 || rect.height === 0) {488 return null489 }490 let clip = {491 x: rect.left,492 y: rect.top,493 width: rect.width,494 height: rect.height,495 scale: 1,496 }497 let screenshotOpts = Object.assign({}, opts, {clip})498 const {data} = await this.client.Page.captureScreenshot(screenshotOpts)499 buffer = Buffer.from(data, 'base64')500 } finally {501 emulation.reset()502 }503 return buffer504 }505 async screenshotMultipleSelectors (selectors, callback, options = {}) {506 return this._screenshotMultipleSelectors(selectors, callback, options)507 }508 async _screenshotMultipleSelectors (selectors, callback, options = {}) {509 const defaults = {510 model: 'scroll',511 format: 'png',512 quality: undefined,513 fromSurface: true,514 useDeviceResolution: false,515 useQuerySelectorAll: false,516 }517 const opts = Object.assign({}, defaults, options)518 const emulation = await createFullscreenEmulationManager(this, 'scroll', true, opts.useDeviceResolution)519 await emulation.emulate()520 try {521 for (let selIdx = 0; selIdx < selectors.length; selIdx++) {522 let selector = selectors[selIdx]523 try {524 let rects = null525 if (opts.useQuerySelectorAll) {526 rects = await this.rectAll(selector)527 // remove elements that has 'display: none'528 rects = rects.filter(rect => rect.width !== 0 && rect.height !== 0)529 } else {530 const r = await this.getBoundingClientRect(selector)531 if (r && r.width !== 0 && r.height !== 0) {532 rects = [r]533 }534 }535 if (rects.length === 0) {536 const err = {reason: 'notfound', message: `selector is not found. selector=${selector}`}537 await callback.apply(this, [err, null, selIdx, selectors])538 continue539 }540 for (let rectIdx = 0; rectIdx < rects.length; rectIdx++) {541 const rect = rects[rectIdx]542 let clip = {543 x: rect.left,544 y: rect.top,545 width: rect.width,546 height: rect.height,547 scale: 1,548 }549 let screenshotOpts = Object.assign({550 format: opts.format,551 quality: opts.quality,552 fromSurface: opts.fromSurface,553 clip,554 })555 const {data} = await this.client.Page.captureScreenshot(screenshotOpts)556 let buffer = Buffer.from(data, 'base64')557 await callback.apply(this, [null, buffer, selIdx, selectors, rectIdx])558 }559 } catch (e) {560 await callback.apply(this, [e, null, selIdx, selectors])561 }562 }563 } finally {564 await emulation.reset()565 await this._restoreEmulationSetting()566 }567 }568 async pdf (options = {}) {569 const {data} = await this.client.Page.printToPDF(options)570 return Buffer.from(data, 'base64')571 }572 async startScreencast (callback, options = {}) {573 await this.client.Page.screencastFrame(async (payload) => {574 await callback.apply(this, [payload])575 await this.client.Page.screencastFrameAck({sessionId: payload.sessionId})576 })577 await this.client.Page.startScreencast(options)578 }579 async stopScreencast () {580 await this.client.Page.stopScreencast()581 }582 // deprecated since 0.3.4583 async requestWillBeSent (callback) {584 await this._checkStart()585 await this.client.Network.requestWillBeSent(callback)586 }587 async send (event, parameter) {588 await this._checkStart()589 return this.client.send(event, parameter)590 }591 async on (event, callback) {592 await this._checkStart()593 this.client.on(event, callback)594 }595 async once (event, callback) {596 await this._checkStart()597 this.client.once(event, callback)598 }599 async removeListener (event, callback) {600 await this._checkStart()601 this.client.removeListener(event, callback)602 }603 async removeAllListeners (event) {604 await this._checkStart()605 this.client.removeAllListeners(event)606 }607 async inject (type, fileOrBuffer) {608 const data = fileOrBuffer instanceof Buffer ? fileOrBuffer.toString('utf8') : await new Promise((resolve, reject) => {609 fs.readFile(fileOrBuffer, {encoding: 'utf-8'}, (err, data) => {610 if (err) reject(err)611 resolve(data)612 })613 }).catch(e => {614 throw e615 })616 if (type === 'js') {617 let script = data.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/(\r|\n)/g, '\\n')618 let expr = `619 {620 let script = document.createElement('script')621 script.type = 'text/javascript'622 script.innerHTML = '${script}'623 document.body.appendChild(script)624 }625 `626 return this.evaluate(expr)627 } else if (type === 'css') {628 let style = data.replace(/`/g, '\\`').replace(/\\/g, '\\\\') // .replace(/(\r|\n)/g, ' ')629 let expr = `630 {631 let style = document.createElement('style')632 style.type = 'text/css'633 style.innerText = \`634 ${style}635 \`636 document.head.appendChild(style)637 }638 `639 return this.evaluate(expr)640 } else {641 throw new Error('found invalid type.')642 }643 }644 async setDeviceScaleFactor (deviceScaleFactor) {645 const screen = await this._getScreenInfo()646 if (screen.devicePixelRatio === deviceScaleFactor) {647 return648 }649 this.currentDeviceScaleFactor = deviceScaleFactor650 return this.client.Emulation.setDeviceMetricsOverride({651 width: 0, height: 0, deviceScaleFactor: deviceScaleFactor, mobile: false,652 })653 }654 async emulate (deviceName) {655 await this._checkStart()656 if (!this.emulateMode) {657 this.userAgentBeforeEmulate = await this.evaluate('return navigator.userAgent')658 }659 const device = devices[deviceName]660 await this.client.Emulation.setDeviceMetricsOverride({661 width: device.width,662 height: device.height,663 deviceScaleFactor: device.deviceScaleFactor,664 mobile: device.mobile,665 fitWindow: false,666 scale: device.pageScaleFactor,667 })668 const platform = device.mobile ? 'mobile' : 'desktop'669 await this.client.Emulation.setTouchEmulationEnabled({enabled: true, configuration: platform})670 await this.userAgent(device.userAgent)671 this.currentEmulateDeviceName = deviceName672 this.emulateMode = true673 }674 async clearEmulate () {675 await this.client.Emulation.clearDeviceMetricsOverride()676 await this.client.Emulation.setTouchEmulationEnabled({enabled: false})677 if (this.userAgentBeforeEmulate) {678 await this.userAgent(this.userAgentBeforeEmulate)679 }680 this.emulateMode = false681 this.currentEmulateDeviceName = null682 }683 async _restoreEmulationSetting () {684 // restore emulation mode685 if (this.currentEmulateDeviceName !== null) {686 await this.emulate(this.currentEmulateDeviceName)687 }688 if (this.currentDeviceScaleFactor) {689 await this.setDeviceScaleFactor(this.currentDeviceScaleFactor)690 }691 }692 async blockUrls (urls) {693 await this._checkStart()694 await this.client.Network.setBlockedURLs({urls: urls})695 }696 async clearBrowserCache () {697 await this._checkStart()698 await this.client.Network.clearBrowserCache()699 }700 async setCookie (params) {701 await this._checkStart()702 let paramArray = null703 if (Array.isArray(params)) {704 paramArray = params705 } else {706 paramArray = [params]707 }708 const currentUrl = await this.evaluate(_ => { return location.href })709 paramArray = paramArray.map(obj => {710 if (obj.url) {711 return obj712 } else {713 obj.url = currentUrl714 return obj715 }716 })717 for (let i in paramArray) {718 const item = paramArray[i]719 await this.client.Network.setCookie(item)720 }721 }722 async getCookies (name = null) {723 await this._checkStart()724 const ck = await this.client.Network.getCookies()725 if (name !== null) {726 for (let i in ck.cookies) {727 if (ck.cookies[i].name === name) return ck.cookies[i]728 }729 } else {730 return ck.cookies731 }732 }733 async deleteCookie (name, url = null) {734 await this._checkStart()735 let nameArray = null736 if (Array.isArray(name)) {737 nameArray = name738 } else {739 nameArray = [name]740 }741 let paramUrl = url742 if (!url) {743 paramUrl = await this.evaluate(_ => { return location.href })744 }745 for (let i in nameArray) {746 const n = nameArray[i]747 await this.client.Network.deleteCookie({cookieName: n, url: paramUrl})748 }749 }750 async clearAllCookies () {751 await this._checkStart()752 await this.client.Network.clearBrowserCookies()753 }754 async getDOMCounters () {755 return await this.client.Memory.getDOMCounters()756 }757 async clearDataForOrigin (origin = null, type = 'all') {758 if (origin === null) {759 origin = await this.evaluate(_ => { return location.origin })760 }761 return await this.client.Storage.clearDataForOrigin({origin: origin, storageTypes: type})762 }763 async _checkStart (startingUrl = null) {764 if (this.client === null) {765 await this.start(startingUrl)...
content.js
Source:content.js
...37 localStorage.setItem(key, css);38 }39 addStyle(css);40}41function _checkStart() {42 if ($('img[src^="/ui/x/"]').length >= 1) {43 clearInterval(_checkStartId);44 onStart();45 }46}47function _startObeserver(cbOnChange) {48 var bodyList = document.querySelector("body");49 50 var observer = new MutationObserver(function(mutations) {51 cbOnChange();52 });53 54 var config = {55 childList: true,...
Card.js
Source:Card.js
1export default class Card {2 constructor(3 company,4 cardNumber,5 validity,6 budget,7 limit,8 checkStart,9 checkEnd10 ) {11 this._company = company;12 this._cardNumber = cardNumber;13 this._validity = validity;14 this._budget = budget;15 this._limit = limit;16 this._checkStart = checkStart;17 this._checkEnd = checkEnd;18 }19 get company() {20 return this._company;21 }22 get cardNumber() {23 return this._cardNumber;24 }25 get validity() {26 return this._validity;27 }28 get budget() {29 return this._budget;30 }31 get limit() {32 return this._limit;33 }34 get checkStart() {35 return this._checkStart;36 }37 get checkEnd() {38 return this._checkEnd;39 }40 set budget(value) {41 this._budget = value;42 }43 set limit(value) {44 this._limit = value;45 }46}47export const createCard = (48 company,49 cardNumber,50 validity,51 budget,52 limit,53 checkStart,54 checkEnd55) => {56 return new Card(57 company,58 cardNumber,59 validity,60 budget,61 limit,62 checkStart,63 checkEnd64 );65};66// export const getCard = async (company, cardNumber) => {67// return await findCard(company, cardNumber);68// }69//70// export const getAllCard = async () => {71// return await findAllCard();...
Using AI Code Generation
1var chromy = new Chromy()2chromy.chain()3 .evaluate(function () {4 })5 .result(function (r) {6 console.log(r)7 })8 .end()9 .then(function () {10 chromy.close()11 })
Using AI Code Generation
1const chromy = new Chromy();2chromy.chain()3 .evaluate(() => {4 return document.querySelector('h1').textContent5 })6 .result((v) => {7 })8 .end()9 .then(() => chromy.close())10### `chromy.chain().goto(url, options)`11Navigate to `url`. `options` can be passed to the underlying `goto` function. See [Puppeteer API](
Using AI Code Generation
1const chromy = require('chromy');2 .chain()3 .evaluate(() => {4 return new Promise((resolve, reject) => {5 setTimeout(() => {6 resolve('success');7 }, 2000);8 });9 })10 .end()11 .then((result) => {12 console.log(result);13 })14 .catch((err) => {15 console.log(err);16 });17const chromy = require('chromy');18const _checkStart = chromy.prototype._checkStart;19chromy.prototype._checkStart = function () {20 _checkStart.call(this);21 this._client.on('Network.requestWillBeSent', (params) => {22 console.log(params.request.url);23 });24};25module.exports = chromy;
Using AI Code Generation
1chromy._checkStart()2checkStart () {3 if (!this._isStarted) {4 throw new Error('Chromy must be started')5 }6}7_checkStart () {8 if (!this._isStarted) {9 throw new Error('Chromy must be started')10 }11}12_checkStart () {13 if (!this._isStarted) {14 throw new Error('Chromy must be started')15 }16}
Using AI Code Generation
1const chromy = require('chromy');2chromy = new chromy();3chromy._checkStart();4chromy.close();5_checkStart(){6 const self = this;7 if(!self._isStarted){8 throw new Error('Chromy is not started');9 }10}11Your name to display (optional):12Your name to display (optional):13chromy = new chromy();14chromy._isStarted();15Your name to display (optional):
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!