How to use _createDetachedInstance 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.

firefox.js

Source: firefox.js Github

copy
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.open = exports._createDetachedInstance = void 0;
4const tslib_1 = require("tslib");
5const lodash_1 = (0, tslib_1.__importDefault)(require("lodash"));
6const bluebird_1 = (0, tslib_1.__importDefault)(require("bluebird"));
7const fs_extra_1 = (0, tslib_1.__importDefault)(require("fs-extra"));
8const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
9const get_port_1 = (0, tslib_1.__importDefault)(require("get-port"));
10const path_1 = (0, tslib_1.__importDefault)(require("path"));
11const url_1 = (0, tslib_1.__importDefault)(require("url"));
12const browsers_1 = require("../../../launcher/lib/browsers");
13const firefox_profile_1 = (0, tslib_1.__importDefault)(require("firefox-profile"));
14const firefox_util_1 = (0, tslib_1.__importDefault)(require("./firefox-util"));
15const utils_1 = (0, tslib_1.__importDefault)(require("./utils"));
16const launcherDebug = (0, tslib_1.__importStar)(require("../../../launcher/lib/log"));
17const events_1 = require("events");
18const os_1 = (0, tslib_1.__importDefault)(require("os"));
19const tree_kill_1 = (0, tslib_1.__importDefault)(require("tree-kill"));
20const mime_db_1 = (0, tslib_1.__importDefault)(require("mime-db"));
21const protocol_1 = require("./protocol");
22const errors = require('../errors');
23const debug = (0, debug_1.default)('cypress:server:browsers:firefox');
24// used to prevent the download prompt for the specified file types.
25// this should cover most/all file types, but if it's necessary to
26// discover more, open Firefox DevTools, download the file yourself
27// and observe the Response Headers content-type in the Network tab
28const downloadMimeTypes = Object.keys(mime_db_1.default).filter((mimeType) => {
29    var _a;
30    return (_a = mime_db_1.default[mimeType].extensions) === null || _a === void 0 ? void 0 : _a.length;
31}).join(',');
32const defaultPreferences = {
33    /**
34     * Taken from https://github.com/puppeteer/puppeteer/blob/8b49dc62a62282543ead43541316e23d3450ff3c/lib/Launcher.js#L520
35     * with minor modifications
36     * BEGIN: Copyright 2017 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0
37     */
38    // Make sure Shield doesn't hit the network.
39    'app.normandy.api_url': '',
40    // Disable Firefox old build background check
41    'app.update.checkInstallTime': false,
42    // Disable automatically upgrading Firefox
43    'app.update.disabledForTesting': true,
44    // Increase the APZ content response timeout to 1 minute
45    'apz.content_response_timeout': 60000,
46    // Prevent various error message on the console
47    // jest-puppeteer asserts that no error message is emitted by the console
48    'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cm,-fp',
49    // Enable the dump function: which sends messages to the system
50    // console
51    // https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
52    'browser.dom.window.dump.enabled': true,
53    // Disable topstories
54    'browser.newtabpage.activity-stream.feeds.section.topstories': false,
55    // Always display a blank page
56    'browser.newtabpage.enabled': false,
57    // Background thumbnails in particular cause grief: and disabling
58    // thumbnails in general cannot hurt
59    'browser.pagethumbnails.capturing_disabled': true,
60    // Disable safebrowsing components.
61    'browser.safebrowsing.blockedURIs.enabled': false,
62    'browser.safebrowsing.downloads.enabled': false,
63    'browser.safebrowsing.malware.enabled': false,
64    'browser.safebrowsing.passwords.enabled': false,
65    'browser.safebrowsing.phishing.enabled': false,
66    // Disable updates to search engines.
67    'browser.search.update': false,
68    // Do not restore the last open set of tabs if the browser has crashed
69    'browser.sessionstore.resume_from_crash': false,
70    // Skip check for default browser on startup
71    'browser.shell.checkDefaultBrowser': false,
72    // Disable newtabpage
73    'browser.startup.homepage': 'about:blank',
74    // Do not redirect user when a milstone upgrade of Firefox is detected
75    'browser.startup.homepage_override.mstone': 'ignore',
76    // Start with a blank page about:blank
77    'browser.startup.page': 0,
78    // Do not allow background tabs to be zombified on Android: otherwise for
79    // tests that open additional tabs: the test harness tab itself might get
80    // unloaded
81    'browser.tabs.disableBackgroundZombification': false,
82    // Do not warn when closing all other open tabs
83    'browser.tabs.warnOnCloseOtherTabs': false,
84    // Do not warn when multiple tabs will be opened
85    'browser.tabs.warnOnOpen': false,
86    // Disable the UI tour.
87    'browser.uitour.enabled': false,
88    // Turn off search suggestions in the location bar so as not to trigger
89    // network connections.
90    'browser.urlbar.suggest.searches': false,
91    // Disable first run splash page on Windows 10
92    'browser.usedOnWindows10.introURL': '',
93    // Do not warn on quitting Firefox
94    'browser.warnOnQuit': false,
95    // Do not show datareporting policy notifications which can
96    // interfere with tests
97    'datareporting.healthreport.about.reportUrl': '',
98    'datareporting.healthreport.documentServerURI': '',
99    'datareporting.healthreport.logging.consoleEnabled': false,
100    'datareporting.healthreport.service.enabled': false,
101    'datareporting.healthreport.service.firstRun': false,
102    'datareporting.healthreport.uploadEnabled': false,
103    'datareporting.policy.dataSubmissionEnabled': false,
104    'datareporting.policy.dataSubmissionPolicyAccepted': false,
105    'datareporting.policy.dataSubmissionPolicyBypassNotification': true,
106    // DevTools JSONViewer sometimes fails to load dependencies with its require.js.
107    // This doesn't affect Puppeteer but spams console (Bug 1424372)
108    'devtools.jsonview.enabled': false,
109    // Disable popup-blocker
110    'dom.disable_open_during_load': false,
111    // Enable the support for File object creation in the content process
112    // Required for |Page.setFileInputFiles| protocol method.
113    'dom.file.createInChild': true,
114    // Disable the ProcessHangMonitor
115    'dom.ipc.reportProcessHangs': false,
116    // Disable slow script dialogues
117    'dom.max_chrome_script_run_time': 0,
118    'dom.max_script_run_time': 0,
119    // Only load extensions from the application and user profile
120    // AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
121    'extensions.autoDisableScopes': 0,
122    'extensions.enabledScopes': 5,
123    // Disable metadata caching for installed add-ons by default
124    'extensions.getAddons.cache.enabled': false,
125    // Disable installing any distribution extensions or add-ons.
126    'extensions.installDistroAddons': false,
127    // Disabled screenshots extension
128    'extensions.screenshots.disabled': true,
129    // Turn off extension updates so they do not bother tests
130    'extensions.update.enabled': false,
131    // Turn off extension updates so they do not bother tests
132    'extensions.update.notifyUser': false,
133    // Make sure opening about:addons will not hit the network
134    'extensions.webservice.discoverURL': '',
135    // Allow the application to have focus even it runs in the background
136    'focusmanager.testmode': true,
137    // Disable useragent updates
138    'general.useragent.updates.enabled': false,
139    // Always use network provider for geolocation tests so we bypass the
140    // macOS dialog raised by the corelocation provider
141    'geo.provider.testing': true,
142    // Do not scan Wifi
143    'geo.wifi.scan': false,
144    // No hang monitor
145    'hangmonitor.timeout': 0,
146    // Show chrome errors and warnings in the error console
147    'javascript.options.showInConsole': true,
148    // Disable download and usage of OpenH264: and Widevine plugins
149    'media.gmp-manager.updateEnabled': false,
150    // Prevent various error message on the console
151    // jest-puppeteer asserts that no error message is emitted by the console
152    'network.cookie.cookieBehavior': 0,
153    // Do not prompt for temporary redirects
154    'network.http.prompt-temp-redirect': false,
155    // Disable speculative connections so they are not reported as leaking
156    // when they are hanging around
157    'network.http.speculative-parallel-limit': 0,
158    // Do not automatically switch between offline and online
159    'network.manage-offline-status': false,
160    // Make sure SNTP requests do not hit the network
161    'network.sntp.pools': '',
162    // Disable Flash.
163    'plugin.state.flash': 0,
164    'privacy.trackingprotection.enabled': false,
165    // Enable Remote Agent
166    // https://bugzilla.mozilla.org/show_bug.cgi?id=1544393
167    'remote.enabled': true,
168    // Don't do network connections for mitm priming
169    'security.certerrors.mitm.priming.enabled': false,
170    // Local documents have access to all other local documents,
171    // including directory listings
172    'security.fileuri.strict_origin_policy': false,
173    // Do not wait for the notification button security delay
174    'security.notification_enable_delay': 0,
175    // Ensure blocked updates do not hit the network
176    'services.settings.server': '',
177    // Do not automatically fill sign-in forms with known usernames and
178    // passwords
179    'signon.autofillForms': false,
180    // Disable password capture, so that tests that include forms are not
181    // influenced by the presence of the persistent doorhanger notification
182    'signon.rememberSignons': false,
183    // Disable first-run welcome page
184    'startup.homepage_welcome_url': 'about:blank',
185    // Disable first-run welcome page
186    'startup.homepage_welcome_url.additional': '',
187    // Disable browser animations (tabs, fullscreen, sliding alerts)
188    'toolkit.cosmeticAnimations.enabled': false,
189    'toolkit.telemetry.server': `''`,
190    // Prevent starting into safe mode after application crashes
191    'toolkit.startup.max_resumed_crashes': -1,
192    /**
193     * END: Copyright 2017 Google Inc. All rights reserved.
194     */
195    'network.proxy.type': 1,
196    // necessary for adding extensions
197    'devtools.debugger.remote-enabled': true,
198    // bind foxdriver to 127.0.0.1
199    'devtools.debugger.remote-host': '127.0.0.1',
200    // devtools.debugger.remote-port is set per-launch
201    'devtools.debugger.prompt-connection': false,
202    // "devtools.debugger.remote-websocket": true
203    'devtools.chrome.enabled': true,
204    'app.update.auto': false,
205    'app.update.enabled': false,
206    'browser.displayedE10SNotice': 4,
207    'browser.download.manager.showWhenStarting': false,
208    'browser.EULA.override': true,
209    'browser.EULA.3.accepted': true,
210    'browser.link.open_external': 2,
211    'browser.link.open_newwindow': 2,
212    'browser.offline': false,
213    'browser.reader.detectedFirstArticle': true,
214    'browser.selfsupport.url': '',
215    'browser.tabs.warnOnClose': false,
216    'devtools.errorconsole.enabled': true,
217    'extensions.blocklist.enabled': false,
218    'extensions.checkCompatibility.nightly': false,
219    'extensions.logging.enabled': true,
220    'javascript.enabled': true,
221    'network.http.phishy-userpass-length': 255,
222    'offline-apps.allow_by_default': true,
223    'prompts.tab_modal.enabled': false,
224    'security.fileuri.origin_policy': 3,
225    'toolkit.networkmanager.disable': true,
226    'toolkit.telemetry.prompted': 2,
227    'toolkit.telemetry.enabled': false,
228    'toolkit.telemetry.rejected': true,
229    'xpinstall.signatures.required': false,
230    'xpinstall.whitelist.required': false,
231    'browser.laterrun.enabled': false,
232    'browser.newtab.url': 'about:blank',
233    'dom.report_all_js_exceptions': true,
234    'network.captive-portal-service.enabled': false,
235    'security.csp.enable': false,
236    'webdriver_accept_untrusted_certs': true,
237    'webdriver_assume_untrusted_issuer': true,
238    'toolkit.legacyUserProfileCustomizations.stylesheets': true,
239    // setting to true hides system window bar, but causes weird resizing issues.
240    'browser.tabs.drawInTitlebar': false,
241    // allow playing videos w/o user interaction
242    'media.autoplay.default': 0,
243    'browser.safebrowsing.enabled': false,
244    // allow capturing screen through getUserMedia(...)
245    // and auto-accept the permissions prompt
246    'media.getusermedia.browser.enabled': true,
247    'media.navigator.permission.disabled': true,
248    'dom.min_background_timeout_value': 4,
249    'dom.timeout.enable_budget_timer_throttling': false,
250    // allow getUserMedia APIs on insecure domains
251    'media.devices.insecure.enabled': true,
252    'media.getusermedia.insecure.enabled': true,
253    'marionette.log.level': launcherDebug.log.enabled ? 'Debug' : undefined,
254    // where to download files
255    // 0: desktop
256    // 1: default "Downloads" directory
257    // 2: directory specified with 'browser.download.dir' (set dynamically below)
258    'browser.download.folderList': 2,
259    // prevents the download prompt for the specified types of files
260    'browser.helperApps.neverAsk.saveToDisk': downloadMimeTypes,
261};
262const FIREFOX_HEADED_USERCSS = `\
263#urlbar:not(.megabar), #urlbar.megabar > #urlbar-background, #searchbar {
264  background: -moz-Field !important;
265  color: -moz-FieldText !important;
266}`;
267const FIREFOX_HEADLESS_USERCSS = `\
268#urlbar {
269  height: 0px !important;
270  min-height: 0px !important;
271  overflow: hidden !important;
272}
273#toolbar {
274  height: 0px !important;
275  min-height: 0px !important;
276  overflow: hidden !important;
277}
278toolbar {
279  height: 0px !important;
280  min-height: 0px !important;
281  overflow: hidden !important;
282}
283#titlebar {
284  height: 0px !important;
285  min-height: 0px !important;
286  overflow: hidden !important;
287  display: none;
288}
289
290`;
291function _createDetachedInstance(browserInstance) {
292    const detachedInstance = new events_1.EventEmitter();
293    detachedInstance.pid = browserInstance.pid;
294    // kill the entire process tree, from the spawned instance up
295    detachedInstance.kill = () => {
296        (0, tree_kill_1.default)(browserInstance.pid, (err, result) => {
297            debug('force-exit of process tree complete %o', { err, result });
298            detachedInstance.emit('exit');
299        });
300    };
301    return detachedInstance;
302}
303exports._createDetachedInstance = _createDetachedInstance;
304function open(browser, url, options = {}, automation) {
305    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
306        // see revision comment here https://wiki.mozilla.org/index.php?title=WebDriver/RemoteProtocol&oldid=1234946
307        const hasCdp = browser.majorVersion >= 86;
308        const defaultLaunchOptions = utils_1.default.getDefaultLaunchOptions({
309            extensions: [],
310            preferences: lodash_1.default.extend({}, defaultPreferences),
311            args: [
312                '-marionette',
313                '-new-instance',
314                '-foreground',
315                '-start-debugger-server',
316                '-no-remote', // @see https://github.com/cypress-io/cypress/issues/6380
317            ],
318        });
319        let remotePort;
320        if (hasCdp) {
321            remotePort = yield (0, protocol_1.getRemoteDebuggingPort)();
322            defaultLaunchOptions.args.push(`--remote-debugging-port=${remotePort}`);
323        }
324        if (browser.isHeadless) {
325            defaultLaunchOptions.args.push('-headless');
326            // we don't need to specify width/height since MOZ_HEADLESS_ env vars will be set
327            // and the browser will spawn maximized. The user may still supply these args to override
328            // defaultLaunchOptions.args.push('--width=1920')
329            // defaultLaunchOptions.args.push('--height=1081')
330        }
331        debug('firefox open %o', options);
332        const ps = options.proxyServer;
333        if (ps) {
334            let { hostname, port, protocol } = url_1.default.parse(ps);
335            if (port == null) {
336                port = protocol === 'https:' ? '443' : '80';
337            }
338            lodash_1.default.extend(defaultLaunchOptions.preferences, {
339                'network.proxy.allow_hijacking_localhost': true,
340                'network.proxy.http': hostname,
341                'network.proxy.ssl': hostname,
342                'network.proxy.http_port': +port,
343                'network.proxy.ssl_port': +port,
344                'network.proxy.no_proxies_on': '',
345                'browser.download.dir': options.downloadsFolder,
346            });
347        }
348        const ua = options.userAgent;
349        if (ua) {
350            defaultLaunchOptions.preferences['general.useragent.override'] = ua;
351        }
352        const [foxdriverPort, marionettePort,] = yield bluebird_1.default.all([(0, get_port_1.default)(), (0, get_port_1.default)()]);
353        defaultLaunchOptions.preferences['devtools.debugger.remote-port'] = foxdriverPort;
354        defaultLaunchOptions.preferences['marionette.port'] = marionettePort;
355        debug('available ports: %o', { foxdriverPort, marionettePort });
356        const [cacheDir, extensionDest, launchOptions,] = yield bluebird_1.default.all([
357            utils_1.default.ensureCleanCache(browser, options.isTextTerminal),
358            utils_1.default.writeExtension(browser, options.isTextTerminal, options.proxyUrl, options.socketIoRoute),
359            utils_1.default.executeBeforeBrowserLaunch(browser, defaultLaunchOptions, options),
360        ]);
361        if (Array.isArray(launchOptions.extensions)) {
362            launchOptions.extensions.push(extensionDest);
363        }
364        else {
365            launchOptions.extensions = [extensionDest];
366        }
367        const profileDir = utils_1.default.getProfileDir(browser, options.isTextTerminal);
368        const profile = new firefox_profile_1.default({
369            destinationDirectory: profileDir,
370        });
371        debug('firefox directories %o', { path: profile.path(), cacheDir, extensionDest });
372        const xulStorePath = path_1.default.join(profile.path(), 'xulstore.json');
373        // if user has set custom window.sizemode pref or it's the first time launching on this profile, write to xulStore.
374        if (!(yield fs_extra_1.default.pathExists(xulStorePath))) {
375            // this causes the browser to launch maximized, which chrome does by default
376            // otherwise an arbitrary size will be picked for the window size
377            // this will not have an effect after first launch in 'interactive' mode
378            const sizemode = 'maximized';
379            yield fs_extra_1.default.writeJSON(xulStorePath, { 'chrome://browser/content/browser.xhtml': { 'main-window': { 'width': 1280, 'height': 1024, sizemode } } });
380        }
381        launchOptions.preferences['browser.cache.disk.parent_directory'] = cacheDir;
382        for (const pref in launchOptions.preferences) {
383            const value = launchOptions.preferences[pref];
384            profile.setPreference(pref, value);
385        }
386        // TODO: fix this - synchronous FS operation
387        profile.updatePreferences();
388        const userCSSPath = path_1.default.join(profileDir, 'chrome');
389        if (!(yield fs_extra_1.default.pathExists(path_1.default.join(userCSSPath, 'userChrome.css')))) {
390            try {
391                yield fs_extra_1.default.mkdir(userCSSPath);
392            }
393            catch (_a) {
394                // probably the folder already exists, this is fine
395            }
396            // if we're headed we change the yellow automation mode url bar back to a normal color
397            //
398            // if we're headless we use userCss to 'trick' the browser
399            //  into having a consistent browser window size that's near-fullscreen
400            //  however it unfortunately still leaves 1px of padding at the top)
401            //  without this trick there would be ~74px of padding at the top instead of 1px.
402            //
403            // TODO: allow configuring userCss through launchOptions
404            const userCss = options.browser.isHeadless ? FIREFOX_HEADLESS_USERCSS : FIREFOX_HEADED_USERCSS;
405            yield fs_extra_1.default.writeFile(path_1.default.join(profileDir, 'chrome', 'userChrome.css'), userCss);
406        }
407        launchOptions.args = launchOptions.args.concat([
408            '-profile',
409            profile.path(),
410        ]);
411        debug('launch in firefox', { url, args: launchOptions.args });
412        const browserInstance = yield (0, browsers_1.launch)(browser, 'about:blank', launchOptions.args, {
413            // sets headless resolution to 1280x720 by default
414            // user can overwrite this default with these env vars or --height, --width arguments
415            MOZ_HEADLESS_WIDTH: '1280',
416            MOZ_HEADLESS_HEIGHT: '721',
417        });
418        try {
419            yield firefox_util_1.default.setup({ automation, extensions: launchOptions.extensions, url, foxdriverPort, marionettePort, remotePort, onError: options.onError });
420        }
421        catch (err) {
422            errors.throw('FIREFOX_COULD_NOT_CONNECT', err);
423        }
424        if (os_1.default.platform() === 'win32') {
425            // override the .kill method for Windows so that the detached Firefox process closes between specs
426            // @see https://github.com/cypress-io/cypress/issues/6392
427            return _createDetachedInstance(browserInstance);
428        }
429        return browserInstance;
430    });
431}
432exports.open = open;
433
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)