How to use chromeRemoteInterface method in Cypress

Best JavaScript code snippet using cypress

crawler.js

Source:crawler.js Github

copy

Full Screen

1const ChromeRemoteInterface = require('chrome-remote-interface');2const ChromeLauncher = require('chrome-launcher');3const UrlParse = require('url-parse');4const Util = require('util');5const Path = require('path');6const TLDJS = require('tldjs');7const ShuffleArray = require('shuffle-array');8const FS = require('fs');9const ArgParse = require('argparse');10let SITE = null;11let COUNT = 0;12let LANDING_DOMAIN = null;13let COOKIE_FILENAME = null;14let HEADLESS = false;15let OUTPUT_LOGS_FILENAME = null;16let OUTPUT_COOKIE_FILENAME = null;17let PORT = null;18function parseArguments() {19    let parser = new ArgParse.ArgumentParser({20      version: '0.0.1',21      addHelp:true,22      description: 'Argparse example'23    });24    parser.addArgument(25      '--site',26      {27        action: 'store',28        required: true,29        help: 'Domain (e.g., google.com)'30      }31    );32    parser.addArgument(33      '--count',34      {35        action: 'store',36        type: 'int',37        required: true,38        help: 'Number of URLs'39      }40    );41    parser.addArgument(42      '--load-cookies',43      {44        action: 'store',45        defaultValue: null,46        help: 'A JSON file that contains cookies'47      }48    );49    parser.addArgument(50      '--port',51      {52        action: 'store',53        defaultValue: null,54        help: 'Port number Chrome Debugger is listening'55      }56    );57    parser.addArgument(58      '--headless',59      {60        action: 'storeTrue',61        defaultValue: false,62        help: 'Using headless mode in servers'63      }64    );65    parser.addArgument(66      '--output-cookies',67      {68        action: 'store',69        defaultValue: null,70        help: 'A JSON file that will contain the output cookies'71      }72    );73    parser.addArgument(74      '--output-logs',75      {76        action: 'store',77        defaultValue: null,78        help: 'A JSON file that will contain the output logs'79      }80    );81    let args = parser.parseArgs();82    SITE = args.site;83    COUNT = args.count;84    LANDING_DOMAIN = SITE;85    HEADLESS = args.headless;86    COOKIE_FILENAME = args.load_cookies;87    OUTPUT_COOKIE_FILENAME = args.output_cookies;88    OUTPUT_LOGS_FILENAME = args.output_logs;89    PORT = args.port;90}91const DOMAINS = [92    'Inspector',93    'Page',94    'Security',95    'Network',96    'Database',97    'IndexedDB',98    'DOMStorage',99    'ApplicationCache',100    'DOM',101    'CSS',102    'ServiceWorker',103    'Log',104    'Runtime',105    'Debugger',106    'Console'107];108const EXCLUDED_EXTENSIONS = [109    '.zip',110    '.exe',111    '.dmg',112    '.doc',113    '.docx',114    '.odt',115    '.pdf',116    '.rtf',117    '.tex',118    '.mp3',119    '.ogg',120    '.wav',121    '.wma',122    '.7z',123    '.rpm',124    '.gz',125    '.tar',126    '.deb',127    '.iso',128    '.sql',129    '.apk',130    '.jar',131    '.bmp',132    '.gif',133    '.jpg',134    '.jpeg',135    '.png',136    '.ps',137    '.tif',138    '.tiff',139    '.ppt',140    '.pptx',141    '.xls',142    '.xlsx',143    '.dll',144    '.msi'145];146function Browser(port) {147    this.port = port;148}149function BrowserTab(port) {150    this.port = port;151    this.events = [];152}153BrowserTab.prototype.connect = async function() {154    this.tab = await ChromeRemoteInterface.New({port: this.port});155    this.client = await ChromeRemoteInterface({target: this.tab.webSocketDebuggerUrl});156    for (let domain of DOMAINS) {157        try {158            await this.client.send(Util.format("%s.enable", domain), {});159        } catch (ex) {160            console.error(domain, ex.message, ex.stack);161        }162    }163    await this.client.Page.addScriptToEvaluateOnNewDocument({164        source: 'window.alert = function() {}; \165                 window.confirm = function() {}; \166                 window.prompt = function() {};'167    });168    await this.client.Network.setCacheDisabled({169        cacheDisabled: true170    });171}172BrowserTab.prototype.close = async function(timeout=10) {173    let that = this;174    return new Promise(resolve => {175        try {176            that.client.removeAllListeners('event');177            that.client.removeAllListeners('Page.loadEventFired');178            that.client.close(function() {179                ChromeRemoteInterface.Close({180                    port: that.port,181                    id: that.tab.id182                }, function() {183                    resolve();184                });185            });186            setTimeout(resolve, timeout * 1000);187        } catch (ex) {188            console.error(ex.message, ex.stack);189            resolve();190        }191    });192}193BrowserTab.prototype.goto = async function(url, timeout=10) {194    let that = this;195    return new Promise(resolve => {196        try {197            that.client.on('event', function(message) {198                that.events.push(message);199            });200            that.client.Page.loadEventFired(function() {201                resolve();202            });203            that.client.Page.navigate({url: url});204            setTimeout(resolve, timeout * 1000);205        } catch (ex) {206            console.error(ex.message, ex.stack);207            resolve();208        }209    });210}211BrowserTab.prototype.evaluateScript = async function(script, timeout=10) {212    let that = this;213    return new Promise(resolve => {214        try {215            that.client.Runtime.evaluate({216                expression: script,217                returnByValue: true218            }).then(result => {219                resolve(result.result.value);220            }).catch(err => {221                console.error(err);222                resolve(null);223            });224            setTimeout(function() {225                resolve(null);226            }, timeout * 1000);227        } catch (ex) {228            console.error(ex.message, ex.stack);229            resolve(null);230        }231    });232}233Browser.prototype.close = async function() {234    if (PORT === null) {235        try {236            await this.browser.kill();237        } catch (ex) {238            console.error(ex.message, ex.stack);239        }240    }241}242Browser.prototype.launch = async function() {243    if (this.port === null) {244        flags = [245            '--disable-gpu',246            '--no-sandbox',247            '--start-maximized',248            '--ignore-certificate-errors',249            '--password-store=basic'250        ];251        if (HEADLESS)252            flags.push('--headless');253        this.browser = await ChromeLauncher.launch({254            chromeFlags: flags255        });256        this.port = this.browser.port;257        await sleep(10);258    }259}260Browser.prototype.openTab = async function() {261    let browser_tab = new BrowserTab(this.port);262    await browser_tab.connect();263    return browser_tab;264}265module.exports = Browser;266module.exports = BrowserTab;267(async () => {268    parseArguments();269    let result = {270        site: SITE,271        cookies: [],272        pages: []273    };274    let cookies = [];275    if (COOKIE_FILENAME != null) {276        cookies = JSON.parse(FS.readFileSync(COOKIE_FILENAME, 'utf8'));277    }278    let browser = new Browser(PORT);279    await browser.launch();280    let cookie_tab = await browser.openTab();281    for (let cookie of cookies) {282        try {283            await cookie_tab.client.Network.setCookie(cookie);284        } catch (ex) {285            console.error(ex.message, ex.stack);286        }287    }288    await cookie_tab.close();289    let visited_urls = new Set();290    let url_queue = [Util.format('http://%s/', SITE)];291    while (url_queue.length > 0 && visited_urls.size < COUNT) {292        try {293            ShuffleArray(url_queue);294            let url = url_queue.shift().trim();295            if (visited_urls.has(url.toLowerCase()))296                continue;297            let browser_tab = await browser.openTab();298            await browser_tab.goto(url, 10);299            await browser_tab.evaluateScript('window.scrollTo(0, document.body.scrollHeight);');300            await sleep(10);301            if (url === Util.format('http://%s/', SITE)) {302                try {303                    let landing_url = JSON.parse(await browser_tab.evaluateScript('JSON.stringify(document.URL);'));304                    let landing_domain = TLDJS.parse(landing_url).domain;305                    if (landing_domain) {306                        LANDING_DOMAIN = landing_domain;307                    }308                } catch (ex) {309                    console.error(ex.message, ex.stack);310                }311            }312            let links = await extractLinks(browser_tab);313            for (let l of links)314                url_queue.push(l);315            visited_urls.add(url.toLowerCase());316            try {317                let cookies = await browser_tab.client.Network.getAllCookies();318                if (cookies !== null)319                    result.cookies = cookies.cookies;320            } catch (ex) {321                console.error(ex.message, ex.stack);322            }323            await browser_tab.close();324            result.pages.push({325                url: url,326                events: browser_tab.events327            });328        } catch (ex) {329            console.error(ex.message, ex.stack);330        }331    }332    FS.writeFileSync(OUTPUT_LOGS_FILENAME, JSON.stringify(result.pages));333    FS.writeFileSync(OUTPUT_COOKIE_FILENAME, JSON.stringify(result.cookies));334    await browser.close();335})();336async function sleep(seconds) {337    return new Promise((resolve) => setTimeout(resolve, seconds * 1000));338}339async function extractLinks(browser_tab) {340    let urls = new Set();341    try {342        let links = await browser_tab.evaluateScript(343            "link_urls = []; \344            links = document.getElementsByTagName('a'); \345            for (let i = 0; i < links.length; i++) { \346                link_urls.push(links[i].href); \347            } \348            JSON.stringify(link_urls);"349        );350        if (links !== null) {351            for (let url of JSON.parse(links)) {352                try {353                    if (isInternalDomain(url)) {354                        let parsed_url = UrlParse(url);355                        if (EXCLUDED_EXTENSIONS.includes(Path.extname(parsed_url.pathname.trim().toLowerCase())))356                            continue;357                        parsed_url.hash = '';358                        urls.add(parsed_url.toString().trim());359                    }360                } catch (ex) {361                    console.error(ex.message, ex.stack);362                }363            }364        }365    } catch (ex) {366        console.error(ex.message, ex.stack);367    }368    return urls;369}370function isInternalDomain(url) {371    let parsed_url = UrlParse(url);372    if (!["http:", "https:"].includes(parsed_url.protocol.toLowerCase().trim()))373        return false;374    if (parsed_url.hostname) {375        url_domain = parsed_url.hostname.trim().toLowerCase();376        if (url_domain === SITE || url_domain.endsWith('.' + SITE))377            return true;378        if (url_domain === LANDING_DOMAIN || url_domain.endsWith('.' + LANDING_DOMAIN))379            return true;380    }381    return false;...

Full Screen

Full Screen

cri-client.js

Source:cri-client.js Github

copy

Full Screen

...85    };86    const connect = () => {87        cri === null || cri === void 0 ? void 0 : cri.close();88        debug('connecting %o', { target });89        return chromeRemoteInterface({90            target,91            local: true,92        })93            .then((newCri) => {94            cri = newCri;95            connected = true;96            maybeDebugCdpMessages(cri);97            cri.send = bluebird_1.default.promisify(cri.send, { context: cri });98            // @see https://github.com/cyrus-and/chrome-remote-interface/issues/7299            cri._notifier.on('disconnect', reconnect);100        });101    };102    return connect()103        .then(() => {...

Full Screen

Full Screen

screenshot.js

Source:screenshot.js Github

copy

Full Screen

...21      'Your Chrome version is too old, you need at least version 62 to capture screenshots with react-workbench.'22    )23  }24  // connect to chrome25  const client = await chromeRemoteInterface({ port })26  const { DOM, Page } = client27  await Page.enable()28  await DOM.enable()29  return client30}31const getComponentBox = async (client) => {32  const { DOM } = client33  const { root } = await DOM.getDocument()34  const { nodeId } = await DOM.querySelector({35    selector: '#component > *',36    nodeId: root.nodeId,37  })38  const { model } = await DOM.getBoxModel({ nodeId })39  return {...

Full Screen

Full Screen

convertToPng.js

Source:convertToPng.js Github

copy

Full Screen

...63    });64    debug('Started google chrome in headless mode');65    let client;66    try {67        client = await chromeRemoteInterface();68        const pngDataUrl = await getPngFromChrome({69            client,70            url,71            width,72            height,73        });74        return pngDataUrl;75    } catch (error) {76        console.error(error);77    } finally {78        client.close();79        chrome.kill();80    }81};

Full Screen

Full Screen

chromeRemoteInterfaceExtra.js

Source:chromeRemoteInterfaceExtra.js Github

copy

Full Screen

1const ChromeRemoteInterface = require('chrome-remote-interface')2const CRIConnection = require('./connection/CRIConnection')3/**4 * @typedef {Object} CRIOptions5 * @property {?string} [host] - HTTP frontend host. Defaults to localhost6 * @property {?number} [port] - HTTP frontend port. Defaults to 92227 * @property {?boolean} [secure] - HTTPS/WSS frontend. Defaults to false8 * @property {?boolean} [useHostName] - do not perform a DNS lookup of the host. Defaults to false9 * @property {?(function|object|string)} [target] - determines which target this client should attach to. The behavior changes according to the type10 * - a function that takes the array returned by the List method and returns a target or its numeric index relative to the array11 * - a target object like those returned by the New and List methods12 * - a string representing the raw WebSocket URL, in this case host and port are not used to fetch the target list, yet they are used to complete the URL if relative13 * - a string representing the target id14 *15 * Defaults to a function which returns the first available target according to the implementation (note that at most one connection can be established to the same target)16 * @property {?Object} [protocol] - Chrome Debugging Protocol descriptor object. Defaults to use the protocol chosen according to the local option17 * @property {?boolean} [local] -  boolean indicating whether the protocol must be fetched remotely or if the local version must be used. It has no effect if the protocol option is set. Defaults to false18 * @property {?number} [delay] - An optional delay to be applied before emitting events (CRIExtra only option)19 */20/**21 * @param {?CRIOptions} [options]22 * @return {Promise<CRIConnection>}23 */24function CRIExtra (options) {25  return CRIConnection.connect(options || {})26}27/**28 * @type {function(opts: ?CRIOptions, cb: *): Chrome}29 */30CRIExtra.CDP = ChromeRemoteInterface31CRIExtra.Protocol = ChromeRemoteInterface.Protocol32CRIExtra.List = ChromeRemoteInterface.List33CRIExtra.New = ChromeRemoteInterface.New34CRIExtra.Activate = ChromeRemoteInterface.Activate35CRIExtra.Close = ChromeRemoteInterface.Close36CRIExtra.Version = ChromeRemoteInterface.Version...

Full Screen

Full Screen

embed.js

Source:embed.js Github

copy

Full Screen

1var ChromeRemoteInterface = require('chrome-remote-interface');2//var MultiplexServer = require("chrome-remote-multiplex").MultiplexServer;3var MultiplexServer = require("..").MultiplexServer;4var server = new MultiplexServer({5  logging: "debug"6});7var remoteClient = null;8server.listen()9  .then(() => {10    console.log("Connecting client to headless chrome ...");11    return ChromeRemoteInterface({ port: server.options.listenPort })12      .then((_remoteClient) => {13        remoteClient = _remoteClient;14        remoteClient.Network.requestWillBeSent(params => {15          console.log("REQUEST: " + params.request.url);16        });17        18        remoteClient.Runtime.consoleAPICalled((entry) => {19          var str = "";20          entry.args.forEach(function(ro) {21            str += " " + ro.value;22          });23          console.log("CONSOLE API: " + entry.type + " " + str);24          return remoteClient.Runtime.discardConsoleEntries();25        });26        27        // enable events then start!28        return Promise.all([ remoteClient.Network.enable(), remoteClient.Page.enable(), remoteClient.Runtime.enable() ]);29      });30  })31  .then(function() {32    console.log("Visiting URL ...");33    return remoteClient.Page.navigate({ url: "http://www.google.co.uk" });34  })35  .then(() => {36    return new Promise((resolve, reject) => setTimeout(resolve, 1500));37  })...

Full Screen

Full Screen

chrome-wrapper.js

Source:chrome-wrapper.js Github

copy

Full Screen

...16    //拿到一个客户端的实例17    // console.log(chromeInstance.port)18    //得到chrome-remote-interface实例19    //通过chrome-remote-interface可以对Chrome devtool protocol协议进行操作20    const remoteInterface = chromeRemoteInterface(config).then(function (chromeAPI) {21      // console.log(chromeAPI)22      //chromeAPI就是ChromeDevToolsProtocol的接口实例23      //通过chromeAPI可以调用协议中定义的接口24      return chromeAPI25    }).catch(err => {26      throw err;27    });28    // console.log(chromeInstance)29    return Promise.all([chromeInstance, remoteInterface])30  }).catch(error => {31    throw error32  })33  return wrapper34}...

Full Screen

Full Screen

print.js

Source:print.js Github

copy

Full Screen

...10  return chromeLauncher.launch(options);11};12const printToPDF = async ({ port, source, target }) => {13  const options = { port };14  const client = await chromeRemoteInterface(options);15  const { Page } = client;16  try {17    await Page.enable();18    await Page.navigate({ url: source });19    await Page.loadEventFired();20    const { data } = await Page.printToPDF();21    fs.writeFileSync(target, Buffer.from(data, "base64"));22  } finally {23    await client.close();24  }25};26(async () => {27  const source = url.format({28    pathname: path.resolve(__dirname, process.argv[2]),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const CDP = require('chrome-remote-interface');2const fs = require('fs');3const { promisify } = require('util');4const writeFile = promisify(fs.writeFile);5const options = {6};7const test = async () => {8  const client = await CDP(options);9  const { Network, Page, Runtime } = client;10  await Promise.all([Network.enable(), Page.enable()]);11  Page.loadEventFired(async () => {12    const { result } = await Runtime.evaluate({13    });14    await writeFile('google.html', result.value);15    client.close();16  });17};18test();19{20  "scripts": {21  },22  "devDependencies": {

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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