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

qmChrome.js

Source: qmChrome.js Github

copy
1/** @namespace window.qmLog */
2/** @namespace window.qm */
3window.qm.chrome = {
4    debugEnabled: true,
5    chromeDebug: function () {
6        function checkAlarm() {
7            chrome.alarms.getAll(function(alarms) {
8                console.log("all alarms", alarms);
9            })
10        }
11        if (qm.chrome.debugEnabled) {
12            checkAlarm();
13            chrome.windows.getLastFocused(function (window) {
14                console.log("last focused", window);
15            });
16            chrome.windows.getAll(function (windows) {
17                console.log("all windows", windows);
18            });
19            chrome.windows.getCurrent(function (window) {
20                console.log("current window", window);
21            });
22        }
23    },
24    checkTimePastNotificationsAndExistingPopupAndShowPopupIfNecessary: function(alarm) {
25        if(!qm.platform.isChromeExtension()){return;}
26        window.qmLog.debug('showNotificationOrPopupForAlarm alarm: ', null, alarm);
27        if(!qm.userHelper.withinAllowedNotificationTimes()){return false;}
28        if(qm.notifications.getNumberInGlobalsOrLocalStorage()){
29            qm.chrome.createSmallInboxNotification();
30        } else {
31            qm.notifications.refreshAndShowPopupIfNecessary();
32        }
33
34    },
35    createSmallInboxNotification: function (){
36        var notificationId = "inbox";
37        chrome.notifications.create(notificationId, qm.chrome.windowParams.inboxNotificationParams, function (id) {});
38    },
39    createSmallNotificationAndOpenInboxInBackground: function(){
40       qm.chrome.createSmallInboxNotification();
41        var windowParams = qm.chrome.windowParams.fullInboxWindowParams;
42        windowParams.focused = false;
43        qm.chrome.openOrFocusChromePopupWindow(windowParams);
44    },
45    createPopup: function(windowParams){
46        function createPopup(windowParams) {
47            windowParams.url = qm.api.addGlobalParams(windowParams.url);
48            qmLog.info("creating popup window", null, windowParams);
49            chrome.windows.create(windowParams, function (chromeWindow) {
50                qm.storage.setItem('chromeWindowId', chromeWindow.id);
51                chrome.windows.update(chromeWindow.id, { focused: windowParams.focused });
52            });
53        }
54        if(windowParams.url.indexOf('.quantimo.do') !== -1 || windowParams.url.indexOf('popup.html') !== -1){
55            createPopup(windowParams);
56        } else {
57            qm.client.getClientWebsiteUrl(function (fullWebsiteUrl) {
58                windowParams.url = fullWebsiteUrl + windowParams.url;
59                createPopup(windowParams);
60            })
61        }
62    },
63    canShowChromePopups: function(){
64        if(typeof chrome === "undefined" || typeof chrome.windows === "undefined" || typeof chrome.windows.create === "undefined"){
65            qmLog.info("Cannot show chrome popups");
66            return false;
67        }
68        if(qm.getUser() && !qm.getUser().pushNotificationsEnabled){
69            qmLog.info("User has disabled notifications");
70            return false;
71        }
72        return true;
73    },
74    getChromeManifest: function() {if(qm.platform.isChromeExtension()){return chrome.runtime.getManifest();}},
75    getWindowByIdAndFocusOrCreateNewPopup: function(chromeWindowId, windowParams){
76        chrome.windows.get(chromeWindowId, function (chromeWindow) {
77            if (!chrome.runtime.lastError && chromeWindow){
78                if(windowParams.focused){
79                    window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window already open. Focusing...', windowParams );
80                    chrome.windows.update(chromeWindowId, {focused: true});
81                } else {
82                    window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window already open. NOT focusing...', windowParams );
83                }
84            } else {
85                window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: Window NOT already open. Creating one...', windowParams );
86                qm.chrome.createPopup(windowParams);
87            }
88        });
89    },
90    createPopupIfNoWindowIdInLocalStorage: function(windowParams){
91        window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow checking if a window is already open.  new window params: ', null, windowParams );
92        var chromeWindowId = parseInt(qm.storage.getItem(qm.items.chromeWindowId), null);
93        if(!chromeWindowId){
94            window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: No window id from localStorage. Creating one...', windowParams );
95            qm.chrome.createPopup(windowParams);
96            return false;
97        }
98        window.qmLog.info('qm.chrome.openOrFocusChromePopupWindow: window id from localStorage: ' + chromeWindowId, windowParams );
99        return chromeWindowId;
100    },
101    getCurrentWindowAndFocusOrCreateNewPopup: function (windowParams) {
102        chrome.windows.getCurrent(function (window) {
103            console.log("current window", window);
104            if(window && window.type === "popup"){
105                chrome.windows.update(window.id, {focused: true});
106            } else {
107                qm.chrome.createPopup(windowParams);
108            }
109        });
110    },
111    getAllWindowsFocusOrCreateNewPopup: function (windowParams) {
112        qm.userHelper.getUserFromLocalStorageOrApi(function (user) {
113            if(!user.pushNotificationsEnabled){
114                qmLog.pushDebug("Not showing chrome popup because notifications are disabled");
115                return;
116            }
117            console.log("getAllWindowsFocusOrCreateNewPopup");
118            chrome.windows.getAll(function (windows) {
119                for (var i = 0; i < windows.length; i++) {
120                    var window = windows[i];
121                    console.log("current window", window);
122                    if(window.type === "popup"){
123                        console.log("Focusing existing popup", window);
124                        chrome.windows.update(window.id, {focused: true});
125                        return;
126                    }
127                }
128                qm.chrome.createPopup(windowParams);
129            });
130        })
131    },
132    handleNotificationClick: function(notificationId) {
133        window.qmLog.debug('onClicked: notificationId:' + notificationId);
134        var focusWindow = true;
135        if(!qm.platform.isChromeExtension()){return;}
136        if(!notificationId){notificationId = null;}
137        qm.chrome.updateChromeBadge(0);
138        qmLog.info("notificationId: "+ notificationId);
139        /**
140         * @return {boolean}
141         */
142        function IsJsonString(str) {
143            try {
144                JSON.parse(str);
145            } catch (exception) {
146                return false;
147            }
148            return true;
149        }
150        if(notificationId === "moodReportNotification") {
151            qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.facesWindowParams);
152        } else if (notificationId === "signin") {
153            qm.chrome.openLoginWindow();
154        } else if (notificationId && IsJsonString(notificationId)) {
155            qm.chrome.openMeasurementAddWindow(focusWindow, notificationId);
156        } else {
157            qm.chrome.openFullInbox(focusWindow, notificationId);
158        }
159        if(notificationId){chrome.notifications.clear(notificationId);}
160    },
161    initialize: function () {
162        //return;
163        chrome.notifications.onClicked.addListener(function(notificationId) { // Called when the notification is clicked
164            qm.chrome.handleNotificationClick(notificationId);
165        });
166        /** @namespace chrome.extension.onMessage */
167        chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
168            // Handles extension-specific requests that come in, such as a request to upload a new measurement
169            window.qmLog.debug('Received request: ' + request.message, null);
170            if(request.message === "uploadMeasurements") {qm.api.postMeasurements(request.payload, null);}
171        });
172        chrome.runtime.onInstalled.addListener(function () { // Called when the extension is installed
173            qm.chrome.scheduleGenericChromeExtensionNotification();
174            if(!localStorage.getItem(qm.items.introSeen)){qm.chrome.openIntroWindowPopup();}
175        });
176        chrome.alarms.onAlarm.addListener(function (alarm) { // Called when an alarm goes off (we only have one)
177            qmLog.info('onAlarm Listener heard this alarm ', null, alarm);
178            qm.userHelper.getUserFromLocalStorageOrApi(function () {
179                qm.notifications.refreshIfEmptyOrStale(qm.chrome.showRatingOrInboxPopup());
180            });
181        });
182        qm.userHelper.getUserFromLocalStorageOrApi(function () {
183            qm.chrome.showRatingOrInboxPopup();
184        }, function () {
185            qm.chrome.showSignInNotification();
186        });
187    },
188    openIntroWindowPopup: function(){
189        qm.storage.setItem('introSeen', true);
190        qm.chrome.createPopup(qm.chrome.windowParams.introWindowParams);
191    },
192    openOrFocusChromePopupWindow: function (windowParams) {
193        //qm.chrome.chromeDebug();
194        if(!window.qm.chrome.canShowChromePopups()){return;}
195        // var chromeWindowId = qm.chrome.createPopupIfNoWindowIdInLocalStorage(windowParams);
196        // if(!chromeWindowId){return;}
197        //qm.chrome.getCurrentWindowAndFocusOrCreateNewPopup(windowParams);
198        qm.chrome.getAllWindowsFocusOrCreateNewPopup(windowParams);
199        //qm.chrome.getWindowByIdAndFocusOrCreateNewPopup(chromeWindowId, windowParams);
200    },
201    openFullInbox: function (focusWindow, notificationId) {
202        var windowParams = qm.chrome.windowParams.fullInboxWindowParams;
203        if(focusWindow){windowParams.focused = true;}
204        qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.fullInboxWindowParams);
205        console.error('notificationId is not a json object and is not moodReportNotification. Opening Reminder Inbox', notificationId);
206    },
207    openLoginWindow: function(){
208        var windowParams = qm.chrome.windowParams.loginWindowParams;
209        windowParams.focused = true;
210        qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.loginWindowParams);
211    },
212    openMeasurementAddWindow: function (focusWindow, notificationId) {
213        var windowParams = qm.chrome.windowParams.fullInboxWindowParams;
214        if(focusWindow){windowParams.focused = true;}
215        qm.chrome.windowParams.fullInboxWindowParams.url = "index.html#/app/measurement-add/?trackingReminderObject=" + notificationId;
216        qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.fullInboxWindowParams);
217    },
218    scheduleGenericChromeExtensionNotification: function() {
219        var intervalInMinutes = parseInt(qm.storage.getItem(qm.items.notificationInterval) || "60");
220        qmLog.info('scheduleGenericChromeExtensionNotification: Reminder notification interval is ' + intervalInMinutes + ' minutes');
221        var alarmInfo = {periodInMinutes: intervalInMinutes};
222        qmLog.info('scheduleGenericChromeExtensionNotification: clear genericTrackingReminderNotificationAlarm');
223        chrome.alarms.clear("genericTrackingReminderNotificationAlarm");
224        qmLog.info('scheduleGenericChromeExtensionNotification: create genericTrackingReminderNotificationAlarm', null, alarmInfo);
225        chrome.alarms.create("genericTrackingReminderNotificationAlarm", alarmInfo);
226        qmLog.info('Alarm set, every ' + intervalInMinutes + ' minutes');
227    },
228    scheduleChromeExtensionNotificationWithTrackingReminder: function(trackingReminder) {
229        var alarmInfo = {};
230        alarmInfo.when =  trackingReminder.nextReminderTimeEpochSeconds * 1000;
231        alarmInfo.periodInMinutes = trackingReminder.reminderFrequency / 60;
232        var alarmName = qm.chrome.createChromeAlarmNameFromTrackingReminder(trackingReminder);
233        alarmName = JSON.stringify(alarmName);
234        chrome.alarms.getAll(function(alarms) {
235            var hasAlarm = alarms.some(function(oneAlarm) {return oneAlarm.name === alarmName;});
236            if (hasAlarm) {qmLog.info(null, 'Already have an alarm for ' + alarmName, null);}
237            if (!hasAlarm) {
238                chrome.alarms.create(alarmName, alarmInfo);
239                qmLog.info(null, 'Created alarm for alarmName ' + alarmName, null, alarmInfo);
240            }
241        });
242    },
243    createChromeAlarmNameFromTrackingReminder: function (trackingReminder) {
244        return {
245            trackingReminderId: trackingReminder.id,
246            variableName: trackingReminder.variableName,
247            defaultValue: trackingReminder.defaultValue,
248            unitAbbreviatedName: trackingReminder.unitAbbreviatedName,
249            periodInMinutes: trackingReminder.reminderFrequency / 60,
250            reminderStartTime: trackingReminder.reminderStartTime,
251            startTrackingDate: trackingReminder.startTrackingDate,
252            variableCategoryName: trackingReminder.variableCategoryName,
253            valence: trackingReminder.valence,
254            reminderEndTime: trackingReminder.reminderEndTime
255        };
256    },
257    showRatingOrInboxPopup: function () {
258        qm.userHelper.getUserFromLocalStorageOrApi(function (user) {
259            if(!user.pushNotificationsEnabled){
260                qmLog.pushDebug("Not showing chrome popup because notifications are disabled");
261                return;
262            }
263            qm.notifications.refreshIfEmptyOrStale(function () {
264                if(!qm.notifications.getNumberInGlobalsOrLocalStorage()){
265                    qmLog.info("No notifications not opening popup");
266                    return false;
267                }
268                if(qm.getUser().combineNotifications){
269                    qm.chrome.createSmallInboxNotification();
270                    return;
271                }
272                window.trackingReminderNotification = window.qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();
273                if(window.trackingReminderNotification){
274                    qm.chrome.showRatingPopup(window.trackingReminderNotification);
275                } else if (qm.storage.getItem(qm.items.useSmallInbox)) {
276                    qmLog.info("No rating notifications so opening compactInboxWindow popup");
277                    qm.chrome.openOrFocusChromePopupWindow(qm.chrome.windowParams.compactInboxWindowParams);
278                } else if (qm.notifications.getNumberInGlobalsOrLocalStorage()) {
279                    qmLog.info("Got an alarm so checkTimePastNotificationsAndExistingPopupAndShowPopupIfNecessary(alarm)");
280                    qm.chrome.createSmallInboxNotification();
281                }
282            }, function (err) {
283                qmLog.error("Not showing popup because of notification refresh error: "+ err);
284            });
285        });
286    },
287    showRatingPopup: function(trackingReminderNotification){
288        qmLog.info("Opening rating notification popup");
289        var getChromeRatingNotificationParams = function(trackingReminderNotification){
290            if(!trackingReminderNotification){trackingReminderNotification = qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();}
291            return { url: qm.notifications.getRatingNotificationPath(trackingReminderNotification), type: 'panel', top: screen.height - 150,
292                left: screen.width - 380, width: 390, height: 110, focused: true};
293        };
294        if(trackingReminderNotification){
295            window.trackingReminderNotification = trackingReminderNotification;
296        } else {
297            window.trackingReminderNotification = qm.notifications.getMostRecentRatingNotificationNotInSyncQueue();
298        }
299        if(window.trackingReminderNotification){
300            qm.getClientId(function (clientId) {
301                qm.chrome.openOrFocusChromePopupWindow(getChromeRatingNotificationParams(window.trackingReminderNotification));
302            });
303        }
304        window.qm.chrome.updateChromeBadge(0);
305    },
306    showSignInNotification: function() {
307        if(!qm.platform.isChromeExtension()){return;}
308        var notificationId = 'signin';
309        chrome.notifications.create(notificationId, qm.chrome.windowParams.signInNotificationParams, function (id) {});
310    },
311    updateChromeBadge: function(numberOfNotifications){
312        var text = "";
313        if(qm.platform.isChromeExtension() && typeof chrome.browserAction !== "undefined"){
314            if(numberOfNotifications){text = numberOfNotifications.toString();}
315            if(numberOfNotifications > 9){text = "?";}
316            chrome.browserAction.setBadgeText({text: text});
317        }
318    }
319};
320if(typeof screen !== "undefined"){
321    function multiplyScreenHeight(factor) {
322        if(typeof screen === "undefined"){return false;}
323        return parseInt(factor * screen.height);
324    }
325    function multiplyScreenWidth(factor) {
326        if(typeof screen === "undefined"){return false;}
327        return parseInt(factor * screen.height);
328    }
329    qm.chrome.windowParams = {
330        introWindowParams: { url: "index.html#/app/intro", type: 'panel', top: multiplyScreenHeight(0.2), left: multiplyScreenWidth(0.4), width: 450, height: 750, focused: true},
331        facesWindowParams: { url: "android_popup.html", type: 'panel', top: screen.height - 150, left: screen.width - 380, width: 390, height: 110, focused: true},
332        loginWindowParams: { url: "index.html#/app/login", type: 'panel', top: multiplyScreenHeight(0.2), left: multiplyScreenWidth(0.4), width: 450, height: 750, focused: true},
333        fullInboxWindowParams: { url: "index.html#/app/reminders-inbox", type: 'panel', top: screen.height - 800, left: screen.width - 455, width: 450, height: 750},
334        compactInboxWindowParams: { url: "index.html#/app/reminders-inbox-compact", type: 'panel', top: screen.height - 360 - 30, left: screen.width - 350, width: 350, height: 360},
335        inboxNotificationParams: { type: "basic", title: "How are you?", message: "Click to open reminder inbox", iconUrl: "img/icons/icon_700.png", priority: 2},
336        signInNotificationParams: { type: "basic", title: "How are you?", message: "Click to sign in and record a measurement", iconUrl: "img/icons/icon_700.png", priority: 2},
337    };
338}
339if(qm.platform.isChromeExtension()){
340    qm.chrome.initialize();
341}
342
Full Screen

local-chrome.js

Source: local-chrome.js Github

copy
1import browserTools from 'testcafe-browser-tools';
2import { killBrowserProcess } from '../../../../../utils/process';
3import BrowserStarter from '../../../utils/browser-starter';
4import { buildChromeArgs } from './build-chrome-args';
5
6const browserStarter = new BrowserStarter();
7
8export async function start (pageUrl, { browserName, config, cdpPort, tempProfileDir, inDocker }) {
9    const chromeInfo           = await browserTools.getBrowserInfo(config.path || browserName);
10    const chromeOpenParameters = Object.assign({}, chromeInfo);
11
12    chromeOpenParameters.cmd = buildChromeArgs({ config, cdpPort, platformArgs: chromeOpenParameters.cmd, tempProfileDir, inDocker });
13
14    await browserStarter.startBrowser(chromeOpenParameters, pageUrl);
15}
16
17export async function stop ({ browserId }) {
18    // NOTE: Chrome on Linux closes only after the second SIGTERM signall
19    if (!await killBrowserProcess(browserId))
20        await killBrowserProcess(browserId);
21}
22
Full Screen

embed_value.js

Source: embed_value.js Github

copy
1describe("embed links", function(){
2  var objectify = function (str)
3  {
4    var hash = {};
5    var parts = str.split('&');
6    for(var i = 0; i < parts.length; i++)
7    {
8      var keyValue = parts[i].split('=');
9      hash[keyValue[0]] = keyValue[1];
10    }
11    return hash;
12  }
13
14  var checkiFrameCode = function(embedCode, readonly){
15    //turn the code into an html element
16    var $embediFrame = $(embedCode);
17
18    //read and check the frame attributes
19    var width = $embediFrame.attr("width"); 
20    var height = $embediFrame.attr("height"); 
21    var name = $embediFrame.attr("name"); 
22    expect(width).to.be('600');
23    expect(height).to.be('400');
24    expect(name).to.be(readonly ? "embed_readonly" : "embed_readwrite");
25
26    //parse the url
27    var src = $embediFrame.attr("src");
28    var questionMark = src.indexOf("?");
29    var url = src.substr(0,questionMark);
30    var paramsStr = src.substr(questionMark+1);
31    var params = objectify(paramsStr);
32
33    var expectedParams = {
34      showControls:     'true'
35    , showChat:         'true'
36    , showLineNumbers:  'true'
37    , useMonospaceFont: 'false'
38    }
39
40    //check the url
41    if(readonly){
42      expect(url.indexOf("r.") > 0).to.be(true);
43    } else {
44      expect(url).to.be(helper.padChrome$.window.location.href);
45    }
46    
47    //check if all parts of the url are like expected
48    expect(params).to.eql(expectedParams);
49  }
50
51  describe("read and write", function(){
52    //create a new pad before each test run
53    beforeEach(function(cb){
54      helper.newPad(cb);
55      this.timeout(60000);
56    });
57
58    describe("the share link", function(){
59      it("is the actual pad url", function(done){
60        var chrome$ = helper.padChrome$; 
61
62        //open share dropdown
63        chrome$(".buttonicon-embed").click();
64
65        //get the link of the share field + the actual pad url and compare them
66        var shareLink = chrome$("#linkinput").val();
67        var padURL = chrome$.window.location.href;
68        expect(shareLink).to.be(padURL);
69
70        done();
71      });
72    });
73
74    describe("the embed as iframe code", function(){
75      it("is an iframe with the the correct url parameters and correct size", function(done){
76        var chrome$ = helper.padChrome$; 
77
78        //open share dropdown
79        chrome$(".buttonicon-embed").click();
80
81        //get the link of the share field + the actual pad url and compare them
82        var embedCode = chrome$("#embedinput").val();
83        
84        checkiFrameCode(embedCode, false)
85
86        done();
87      });
88    });
89  });
90
91  describe("when read only option is set", function(){
92    beforeEach(function(cb){
93      helper.newPad(cb);
94      this.timeout(60000);
95    });
96
97    describe("the share link", function(){
98      it("shows a read only url", function(done){
99        var chrome$ = helper.padChrome$; 
100
101        //open share dropdown
102        chrome$(".buttonicon-embed").click();
103        chrome$('#readonlyinput').click();
104        chrome$('#readonlyinput:checkbox:not(:checked)').attr('checked', 'checked');
105
106        //get the link of the share field + the actual pad url and compare them
107        var shareLink = chrome$("#linkinput").val();
108        var containsReadOnlyLink = shareLink.indexOf("r.") > 0
109        expect(containsReadOnlyLink).to.be(true);
110
111        done();
112      });
113    });
114
115    describe("the embed as iframe code", function(){
116      it("is an iframe with the the correct url parameters and correct size", function(done){
117        var chrome$ = helper.padChrome$; 
118
119        //open share dropdown
120        chrome$(".buttonicon-embed").click();
121        //check read only checkbox, a bit hacky
122        chrome$('#readonlyinput').click();
123        chrome$('#readonlyinput:checkbox:not(:checked)').attr('checked', 'checked');
124
125
126        //get the link of the share field + the actual pad url and compare them
127        var embedCode = chrome$("#embedinput").val();
128        
129        checkiFrameCode(embedCode, true);
130        
131        done();
132      });
133    });
134
135  });
136});
137
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)