How to use this._navigateUsingCRI method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

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

chrome.js

Source: chrome.js Github

copy
1(function() {
2  var CHROME_VERSIONS_WITH_BUGGY_ROOT_LAYER_SCROLLING, CHROME_VERSION_INTRODUCING_PROXY_BYPASS_ON_LOOPBACK, CdpAutomation, CriClient, LOAD_EXTENSION, Promise, _, _connectToChromeRemoteInterface, _disableRestorePagesPrompt, _maybeRecordVideo, _navigateUsingCRI, _normalizeArgExtensions, _removeRootExtension, _setAutomation, appData, check, debug, defaultArgs, extension, fs, getRemoteDebuggingPort, la, os, path, pathToExtension, pathToTheme, plugins, pluginsBeforeBrowserLaunch, protocol, utils,
3    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
4    slice = [].slice;
5
6  _ = require("lodash");
7
8  os = require("os");
9
10  path = require("path");
11
12  Promise = require("bluebird");
13
14  la = require('lazy-ass');
15
16  check = require('check-more-types');
17
18  extension = require("../../../extension");
19
20  debug = require("debug")("cypress:server:browsers:chrome");
21
22  plugins = require("../plugins");
23
24  fs = require("../util/fs");
25
26  appData = require("../util/app_data");
27
28  utils = require("./utils");
29
30  protocol = require("./protocol");
31
32  CdpAutomation = require("./cdp_automation").CdpAutomation;
33
34  CriClient = require("./cri-client");
35
36  LOAD_EXTENSION = "--load-extension=";
37
38  CHROME_VERSIONS_WITH_BUGGY_ROOT_LAYER_SCROLLING = "66 67".split(" ");
39
40  CHROME_VERSION_INTRODUCING_PROXY_BYPASS_ON_LOOPBACK = 72;
41
42  pathToExtension = extension.getPathToExtension();
43
44  pathToTheme = extension.getPathToTheme();
45
46  defaultArgs = ["--test-type", "--ignore-certificate-errors", "--start-maximized", "--silent-debugger-extension-api", "--no-default-browser-check", "--no-first-run", "--noerrdialogs", "--enable-fixed-layout", "--disable-popup-blocking", "--disable-password-generation", "--disable-save-password-bubble", "--disable-single-click-autofill", "--disable-prompt-on-repos", "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-renderer-throttling", "--disable-restore-session-state", "--disable-translate", "--disable-new-profile-management", "--disable-new-avatar-menu", "--allow-insecure-localhost", "--reduce-security-for-testing", "--enable-automation", "--disable-device-discovery-notifications", "--disable-infobars", "--autoplay-policy=no-user-gesture-required", "--disable-site-isolation-trials", "--metrics-recording-only", "--disable-prompt-on-repost", "--disable-hang-monitor", "--disable-sync", "--disable-web-resources", "--safebrowsing-disable-auto-update", "--safebrowsing-disable-download-protection", "--disable-client-side-phishing-detection", "--disable-component-update", "--disable-default-apps", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--disable-ipc-flooding-protection", "--disable-backgrounding-occluded-window", "--disable-breakpad", "--password-store=basic", "--use-mock-keychain"];
47
48  getRemoteDebuggingPort = Promise.method(function() {
49    var port;
50    if (port = Number(process.env.CYPRESS_REMOTE_DEBUGGING_PORT)) {
51      return port;
52    }
53    return utils.getPort();
54  });
55
56  pluginsBeforeBrowserLaunch = function(browser, args) {
57    if (!plugins.has("before:browser:launch")) {
58      return args;
59    }
60    return plugins.execute("before:browser:launch", browser, args).then(function(newArgs) {
61      debug("got user args for 'before:browser:launch'", newArgs);
62      return newArgs != null ? newArgs : args;
63    });
64  };
65
66  _normalizeArgExtensions = function(dest, args) {
67    var extensions, loadExtension, userExtensions;
68    loadExtension = _.find(args, function(arg) {
69      return arg.includes(LOAD_EXTENSION);
70    });
71    if (loadExtension) {
72      args = _.without(args, loadExtension);
73      userExtensions = loadExtension.replace(LOAD_EXTENSION, "").split(",");
74    }
75    extensions = [].concat(userExtensions, dest, pathToTheme);
76    args.push(LOAD_EXTENSION + _.compact(extensions).join(","));
77    return args;
78  };
79
80  _removeRootExtension = function() {
81    return fs.removeAsync(appData.path("extensions")).catchReturn(null);
82  };
83
84  _disableRestorePagesPrompt = function(userDir) {
85    var prefsPath;
86    prefsPath = path.join(userDir, "Default", "Preferences");
87    return fs.readJson(prefsPath).then(function(preferences) {
88      var profile;
89      if (profile = preferences.profile) {
90        if (profile["exit_type"] !== "Normal" || profile["exited_cleanly"] !== true) {
91          debug("cleaning up unclean exit status");
92          profile["exit_type"] = "Normal";
93          profile["exited_cleanly"] = true;
94          return fs.writeJson(prefsPath, preferences);
95        }
96      }
97    })["catch"](function() {});
98  };
99
100  _connectToChromeRemoteInterface = function(port) {
101    la(check.userPort(port), "expected port number to connect CRI to", port);
102    debug("connecting to Chrome remote interface at random port %d", port);
103    return protocol.getWsTargetFor(port).then(function(wsUrl) {
104      debug("received wsUrl %s for port %d", wsUrl, port);
105      return CriClient.create(wsUrl);
106    });
107  };
108
109  _maybeRecordVideo = function(options) {
110    return function(client) {
111      if (!options.screencastFrame) {
112        debug("screencastFrame is false");
113        return client;
114      }
115      debug('starting screencast');
116      client.on('Page.screencastFrame', options.screencastFrame);
117      return client.send('Page.startScreencast', {
118        format: 'jpeg'
119      }).then(function() {
120        return client;
121      });
122    };
123  };
124
125  _navigateUsingCRI = function(url) {
126    la(check.url(url), "missing url to navigate to", url);
127    return function(client) {
128      la(client, "could not get CRI client");
129      debug("received CRI client");
130      debug('navigating to page %s', url);
131      return client.send("Page.bringToFront").then(function() {
132        return client.send("Page.navigate", {
133          url: url
134        });
135      });
136    };
137  };
138
139  _setAutomation = function(client, automation) {
140    return automation.use(CdpAutomation(client.send));
141  };
142
143  module.exports = {
144    _normalizeArgExtensions: _normalizeArgExtensions,
145    _removeRootExtension: _removeRootExtension,
146    _connectToChromeRemoteInterface: _connectToChromeRemoteInterface,
147    _maybeRecordVideo: _maybeRecordVideo,
148    _navigateUsingCRI: _navigateUsingCRI,
149    _setAutomation: _setAutomation,
150    _writeExtension: function(browser, isTextTerminal, proxyUrl, socketIoRoute) {
151      return extension.setHostAndPath(proxyUrl, socketIoRoute).then(function(str) {
152        var extensionBg, extensionDest;
153        extensionDest = utils.getExtensionDir(browser, isTextTerminal);
154        extensionBg = path.join(extensionDest, "background.js");
155        return utils.copyExtension(pathToExtension, extensionDest).then(function() {
156          return fs.writeFileAsync(extensionBg, str);
157        })["return"](extensionDest);
158      });
159    },
160    _getArgs: function(options) {
161      var args, majorVersion, ps, ua;
162      if (options == null) {
163        options = {};
164      }
165      _.defaults(options, {
166        browser: {}
167      });
168      args = [].concat(defaultArgs);
169      if (os.platform() === "linux") {
170        args.push("--disable-gpu");
171        args.push("--no-sandbox");
172      }
173      if (ua = options.userAgent) {
174        args.push("--user-agent=" + ua);
175      }
176      if (ps = options.proxyServer) {
177        args.push("--proxy-server=" + ps);
178      }
179      if (options.chromeWebSecurity === false) {
180        args.push("--disable-web-security");
181        args.push("--allow-running-insecure-content");
182      }
183      majorVersion = options.browser.majorVersion;
184      if (indexOf.call(CHROME_VERSIONS_WITH_BUGGY_ROOT_LAYER_SCROLLING, majorVersion) >= 0) {
185        args.push("--disable-blink-features=RootLayerScrolling");
186      }
187      if (majorVersion >= CHROME_VERSION_INTRODUCING_PROXY_BYPASS_ON_LOOPBACK) {
188        args.push("--proxy-bypass-list=<-loopback>");
189      }
190      return args;
191    },
192    open: function(browser, url, options, automation) {
193      var isTextTerminal, userDir;
194      if (options == null) {
195        options = {};
196      }
197      isTextTerminal = options.isTextTerminal;
198      userDir = utils.getProfileDir(browser, isTextTerminal);
199      return Promise["try"]((function(_this) {
200        return function() {
201          var args;
202          args = _this._getArgs(options);
203          return getRemoteDebuggingPort().then(function(port) {
204            args.push("--remote-debugging-port=" + port);
205            return Promise.all([utils.ensureCleanCache(browser, isTextTerminal), pluginsBeforeBrowserLaunch(options.browser, args), port]);
206          });
207        };
208      })(this)).spread((function(_this) {
209        return function(cacheDir, args, port) {
210          return Promise.all([_this._writeExtension(browser, isTextTerminal, options.proxyUrl, options.socketIoRoute), _removeRootExtension(), _disableRestorePagesPrompt(userDir)]).spread(function(extDest) {
211            args = _normalizeArgExtensions(extDest, args);
212            args.push("--user-data-dir=" + userDir);
213            args.push("--disk-cache-dir=" + cacheDir);
214            debug("launching in chrome with debugging port", {
215              url: url,
216              args: args,
217              port: port
218            });
219            return utils.launch(browser, "about:blank", args);
220          }).then(function(launchedBrowser) {
221            la(launchedBrowser, "did not get launched browser instance");
222            return _this._connectToChromeRemoteInterface(port).then(function(criClient) {
223              la(criClient, "expected Chrome remote interface reference", criClient);
224              return criClient.ensureMinimumProtocolVersion('1.3')["catch"](function(err) {
225                throw new Error("Cypress requires at least Chrome 64.\n\nDetails:\n" + err.message);
226              }).then(function() {
227                var originalBrowserKill;
228                _this._setAutomation(criClient, automation);
229                originalBrowserKill = launchedBrowser.kill;
230                launchedBrowser.kill = function() {
231                  var args;
232                  args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
233                  debug("closing remote interface client");
234                  return criClient.close().then(function() {
235                    debug("closing chrome");
236                    return originalBrowserKill.apply(launchedBrowser, args);
237                  });
238                };
239                return criClient;
240              });
241            }).then(_this._maybeRecordVideo(options)).then(_this._navigateUsingCRI(url))["return"](launchedBrowser);
242          });
243        };
244      })(this));
245    }
246  };
247
248}).call(this);
249
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)