How to use isIncognito method in Puppeteer

Best JavaScript code snippet using puppeteer

data-server.js

Source:data-server.js Github

copy

Full Screen

1/**2 * Server to handle message exchanges between the UI and content scripts.3 * @class4 * @requires common/messages.js5 * @requires common/monitor.js6 * @requires background/data-storage.js7 **/8const [DataServer] = (function() {9 "use strict";10 /**11 * @constant {number} Debounce duration in milleseconds.12 **/13 const SEND_GLOBAL_EVENTS_DEBOUNCE_DURATION = 50;14 /**15 * https://davidwalsh.name/javascript-debounce-function16 * @param {function} func - function to wrap with debounce17 * @param {number} wait - debounce time in milliseconds18 * @param {boolean} [immediate] - if true, trigger at start rather than end of debounce period19 **/20 const debounce = function(func, wait, immediate) {21 let timeout;22 return function() {23 const context = this;24 const args = arguments;25 const later = function() {26 timeout = null;27 if (!immediate) {28 func.apply(context, args);29 }30 };31 const callNow = immediate && !timeout;32 clearTimeout(timeout);33 timeout = setTimeout(later, wait);34 if (callNow) {35 func.apply(context, args);36 }37 };38 };39 /**40 * A data server to handle message exchanges between the UI and content scripts.41 * @class42 **/43 const DataServer = function() {44 this.monitor = new Monitor("DataServer");45 this.monitor.KEY_ENTER("DataServer");46 this.dataStorage = new DataStorage();47 this.sendMonitorStatusEvent = debounce(this.sendMonitorStatusEventImmediately, SEND_GLOBAL_EVENTS_DEBOUNCE_DURATION).bind(this);48 this.sendDatabaseEvent = debounce(this.sendDatabaseEventImmediately, SEND_GLOBAL_EVENTS_DEBOUNCE_DURATION).bind(this);49 this.listenToScannerMessages();50 this.listenToUiMessages();51 this.monitor.KEY_EXIT("DataServer");52 };53 // Incoming events from content to background ---------------------------------54 /**55 * @listens Incoming events from the content scripts.56 **/57 DataServer.prototype.listenToScannerMessages = function() {58 const onScannerMessages = (message, sender) => {59 this.monitor.EVENT("browser.runtime.onMessage (scanner)", {"message": message, "sender": sender});60 const key = message.key;61 const tabId = (sender && sender.tab) ? sender.tab.id : null;62 const isIncognito = (sender && sender.tab) ? sender.tab.incognito : null;63 // No operation defined.64 if (MSG.SCANNER.LOADED === key) {65 return;66 }67 // No operation defined.68 if (MSG.SCANNER.UNLOADED === key) {69 return;70 }71 // Relay scanning events to the UI.72 if (MSG.SCANNER.STARTED_SCANNING === key || MSG.SCANNER.FINISHED_SCANNING === key) {73 if (!isIncognito) {74 this.sendScanningStatusEvent(tabId);75 }76 return;77 }78 // Insert new ads into the database.79 // Fire a database update event.80 if (MSG.SCANNER.PARSED_NEW_ADS === key) {81 if (!isIncognito) {82 const newAds = message["newAds"] ? message["newAds"] : [];83 this.insertAdsIntoDatabase(newAds).then(() => {84 this.sendDatabaseEvent();85 });86 }87 return;88 }89 // Insert new ad targeting information into the database.90 // Fire a database update event.91 if (MSG.SCANNER.PARSED_NEW_TARGETS === key) {92 if (!isIncognito) {93 const newTargets = message["newTargets"] ? message["newTargets"] : [];94 this.insertTargetsIntoDatabase(newTargets).then(() => {95 this.sendDatabaseEvent();96 });97 }98 return;99 }100 // Return the current monitor status.101 if (MSG.SCANNER.GET_MONITOR_STATUS === key) {102 if (!isIncognito) {103 return this.getMonitorStatus().then(isEnabled => {104 return {105 "isEnabled": isEnabled,106 };107 });108 }109 else {110 return Promise.resolve({111 "isEnabled": false,112 });113 }114 }115 return;116 };117 this.monitor.EVENT("browser.runtime.onMessage.addListener(onScannerMessages)");118 browser.runtime.onMessage.addListener(onScannerMessages);119 };120 // Outgoing events from background to UI --------------------------------------121 /**122 * Fire an event to notify UI of a change in monitor status.123 **/124 DataServer.prototype.sendMonitorStatusEventImmediately = function() {125 this.monitor.ENTER("sendMonitorStatusEvent");126 const options = {127 "key": MSG.BACKGROUND.MONITOR_STATUS_EVENT,128 };129 this.monitor.OPTIONS(options);130 browser.runtime.sendMessage(options).then(() => {131 this.monitor.EXIT("sendMonitorStatusEvent");132 });133 };134 /**135 * Fire an event to notify UI of an update in the database.136 **/137 DataServer.prototype.sendDatabaseEventImmediately = function() {138 this.monitor.ENTER("sendDatabaseEvent");139 const options = {140 "key": MSG.BACKGROUND.DATABASE_EVENT,141 };142 this.monitor.OPTIONS(options);143 browser.runtime.sendMessage(options).then(() => {144 this.monitor.EXIT("sendDatabaseEvent");145 });146 };147 /**148 * Fire an event to notify UI of a change in scanning status in a tab.149 * @param {string} tabId - Source tab.150 **/151 DataServer.prototype.sendScanningStatusEvent = function(tabId) {152 this.monitor.ENTER("sendScanningStatusEvent");153 const options = {154 "key": MSG.BACKGROUND.SCANNING_STATUS_EVENT,155 "tabId": tabId,156 };157 this.monitor.OPTIONS(options);158 browser.runtime.sendMessage(options).then(() => {159 this.monitor.EXIT("sendScanningStatusEvent");160 });161 };162 // Incoming messages from UI to background ------------------------------163 /**164 * @listens Incoming data requests and actions from the UI.165 **/166 DataServer.prototype.listenToUiMessages = function() {167 const onUiMessages = (message, sender) => {168 this.monitor.EVENT("browser.runtime.onMessage (ui)", {"message": message, "sender": sender});169 const key = message.key;170 const tabId = message.tabId;171 const isIncognito = message.isIncognito;172 // Respond to requests related to persistant data storage.173 if (MSG.UI.GET_MONITOR_STATUS === key) {174 if (!isIncognito) {175 return this.getMonitorStatus().then(isEnabled => {176 return {177 "isEnabled": isEnabled,178 };179 });180 }181 else {182 return Promise.resolve({183 "isEnabled": false,184 });185 }186 }187 // Respond to requests related to persistant data storage.188 if (MSG.UI.GET_ALL_ADS === key) {189 if (!isIncognito) {190 return this.getAllAds().then(allAds => {191 return {192 "allAds": allAds,193 };194 });195 }196 else {197 return Promise.resolve({198 "allAds": [],199 });200 }201 }202 // Respond to requests related to persistant data storage.203 if (MSG.UI.GET_ALL_TARGETS === key) {204 if (!isIncognito) {205 return this.getAllTargets().then(allTargets => {206 return {207 "allTargets": allTargets,208 };209 });210 }211 else {212 return Promise.resolve({213 "allTargets": [],214 });215 }216 }217 // Apply actions to persistant data storage.218 if (MSG.UI.ENABLE_MONITOR === key) {219 if (!isIncognito) {220 this.enableMonitor().then(() => {221 this.sendMonitorStatusEvent();222 });223 }224 return;225 }226 // Apply actions to persistant data storage.227 if (MSG.UI.DISABLE_MONITOR === key) {228 if (!isIncognito) {229 this.disableMonitor().then(() => {230 this.sendMonitorStatusEvent();231 });232 }233 return;234 }235 // Apply actions to persistant data storage.236 if (MSG.UI.CLEAR_DATABASE === key) {237 if (!isIncognito) {238 this.clearDatabase().then(() => {239 this.sendDatabaseEvent();240 });241 }242 return;243 }244 // Relay data requests to the content scripts.245 // Relay responses back to the UI.246 if (MSG.UI.GET_SCANNING_STATUS === key) {247 if (!isIncognito) {248 return this.sendGetScanningStatusMessage(tabId).then(message => {249 return message;250 });251 }252 else {253 return Promise.resolve({});254 }255 }256 // Check monitor status.257 // If enabled, reply actions to the content scripts.258 if (MSG.UI.START_SCANNING === key) {259 if (!isIncognito) {260 this.getMonitorStatus().then(isEnabled => {261 if (isEnabled) {262 this.sendStartScanningMessage(tabId);263 }264 });265 }266 return;267 }268 return;269 };270 this.monitor.EVENT("browser.runtime.onMessage.addListener(onUiMessages)");271 browser.runtime.onMessage.addListener(onUiMessages);272 };273 // Messages from background to content ----------------------------------------274 /**275 * Fire a message to retrieve scanning status from a tab.276 * @returns {boolean} isScanning - Scanning status (on a Facebook page) or undefined otherwise.277 **/278 DataServer.prototype.sendGetScanningStatusMessage = function(tabId) {279 return new Promise(resolve => {280 this.monitor.ENTER("sendGetScanningStatusMessage");281 browser.tabs.sendMessage(tabId, {"key": MSG.BACKGROUND.GET_SCANNING_STATUS}).then(message => {282 this.monitor.RESULTS(message);283 resolve(message);284 this.monitor.EXIT("sendGetScanningStatusMessage");285 }).catch(() => {286 resolve({});287 this.monitor.EXIT("sendGetScanningStatusMessage");288 });289 });290 };291 /**292 * Fire a message to start scanning a page for ads.293 **/294 DataServer.prototype.sendStartScanningMessage = function(tabId) {295 return new Promise(resolve => {296 this.monitor.ENTER("sendStartScanningMessage");297 browser.tabs.sendMessage(tabId, {"key": MSG.BACKGROUND.START_SCANNING}).then(() => {298 resolve();299 this.monitor.EXIT("sendStartScanningMessage");300 }).catch(() => {301 resolve();302 this.monitor.EXIT("sendStartScanningMessage");303 });304 });305 };306 // Database functions: Read-only by UI or scanner -----------------------------307 /**308 * Retrieve a list of all ads in the database.309 * @async310 * @returns {Object[]} List of ads.311 **/312 DataServer.prototype.getAllAds = function() {313 return new Promise(resolve => {314 this.monitor.ENTER("getAllAds");315 this.dataStorage.getAllAds().then(allAds => {316 this.monitor.RESULTS("allAds =", allAds);317 this.monitor.EXIT("getAllAds");318 resolve(allAds);319 });320 });321 };322 /**323 * Retrieve a list of all targets in the database.324 * @async325 * @returns {Object[]} List of targets.326 **/327 DataServer.prototype.getAllTargets = function() {328 return new Promise(resolve => {329 this.monitor.ENTER("getAllTargets");330 this.dataStorage.getAllTargets().then(allTargets => {331 this.monitor.RESULTS("allTargets =", allTargets);332 this.monitor.EXIT("getAllTargets");333 resolve(allTargets);334 });335 });336 };337 /**338 * Retrieve the status of the monitor.339 * @async340 * @returns {boolean} Flag on whether the monitor is enabled.341 **/342 DataServer.prototype.getMonitorStatus = function() {343 return new Promise(resolve => {344 this.monitor.ENTER("getMonitorStatus");345 this.dataStorage.getDisableMonitor().then(isDisabled => {346 this.monitor.RESULTS("isDisabled =", isDisabled);347 this.monitor.EXIT("getMonitorStatus");348 // Default to disabled.349 if (isDisabled === undefined) {350 isDisabled = false;351 }352 // Enabled only if isDisabled is false.353 resolve(isDisabled === false);354 });355 });356 };357 // Database functions: Write to DB by UI --------------------------------------358 /**359 * Clear all ads in the database.360 * @async361 **/362 DataServer.prototype.clearDatabase = function() {363 return new Promise(resolve => {364 this.monitor.ENTER("clearDatabase");365 this.dataStorage.clearAllAds().then(() => {366 this.dataStorage.clearAllTargets().then(() => {367 this.monitor.EXIT("clearDatabase");368 resolve();369 });370 });371 });372 };373 /**374 * Enable the monitor.375 * @async376 **/377 DataServer.prototype.enableMonitor = function() {378 return new Promise(resolve => {379 this.monitor.ENTER("enableMonitor");380 this.dataStorage.setDisableMonitor(false).then(() => {381 this.monitor.EXIT("enableMonitor");382 resolve();383 });384 });385 };386 /**387 * Disable the monitor.388 * @async389 **/390 DataServer.prototype.disableMonitor = function() {391 return new Promise(resolve => {392 this.monitor.ENTER("disableMonitor");393 this.dataStorage.setDisableMonitor(true).then(() => {394 this.monitor.EXIT("disableMonitor");395 resolve();396 });397 });398 };399 // Database functions: Write to DB by content scripts -------------------------400 /**401 * Insert a list of ads into the database.402 * @async403 * @param {Object[]} ads - List of new ads.404 **/405 DataServer.prototype.insertAdsIntoDatabase = function(ads = []) {406 return new Promise(resolve => {407 this.monitor.ENTER("insertAdsIntoDatabase");408 this.monitor.OPTIONS("ads =", ads);409 this.dataStorage.storeAds(ads).then(() => {410 this.monitor.EXIT("insertAdsIntoDatabase");411 resolve();412 });413 });414 };415 /**416 * Insert a list of targets into the database.417 * @async418 * @param {Object[]} targeting - List of new targets.419 **/420 DataServer.prototype.insertTargetsIntoDatabase = function(targets = []) {421 return new Promise(resolve => {422 this.monitor.ENTER("insertTargetsIntoDatabase");423 this.monitor.OPTIONS("targets =", targets);424 this.dataStorage.storeTargets(targets).then(() => {425 this.monitor.EXIT("insertTargetsIntoDatabase");426 resolve();427 });428 });429 };430 return [DataServer];...

Full Screen

Full Screen

create-poll.js

Source:create-poll.js Github

copy

Full Screen

1const Discord = require('discord.js')2const pollSystem = require('../../Polls/polling-system')3const commandBase = require('../command-base')4const customCommands = require('../../custom-commands')5const bot = require('../../bot')6const mongo = require('../../mongo')7const guildConfigSchema = require('../../schema/guild-config')8const embedColor = require('../../embed-color.json')9const reply = require('../../message-reply')10const { defaultTimeout } = require('../../config.json')11module.exports = {12 commands: 'poll',13 category: 'polls',14 description: 'Creates a new poll.',15 permissions: 'ADMINISTRATOR',16 minArgs: 0,17 callback: async (message) => {18 const guildId = message.guild.id19 let config, defChannelId20 customCommands.pushNewUserToIgnore(message.author.id, 'INITIATED CREATE_POLL SEQ.')21 await mongo().then(async mongoose => {22 try {23 config = await guildConfigSchema.findOne({ _id: guildId })24 } finally {25 mongoose.connection.close()26 }27 })28 const prefix = commandBase.getGuildPrefix(guildId)29 const filter = x => x.author.id === message.author.id30 const channel = message.channel31 let isIncognito = false32 const selectTypeEmbed = await channel.send(new Discord.MessageEmbed({33 title: 'Choose Type of Poll',34 description: 'Select the type of poll you would like to create.',35 color: embedColor.STREET_BLUE36 })37 .addField(':regional_indicator_a: - Regular Poll', 'Regular poll where all reactions are visible.')38 .addField(':regional_indicator_b: - Incognito Poll', 'Responses are private and anonymous. Members react via DMs with the bot.')39 )40 await selectTypeEmbed.react('🇦')41 await selectTypeEmbed.react('🇧')42 await selectTypeEmbed.awaitReactions((x => x.emoji.name === '🇦' || x.emoji.name === '🇧'), { max: 1, time: defaultTimeout }).then(async collected => {43 const reaction = collected.first()44 if (reaction.emoji.name === '🇧') {45 isIncognito = true46 }47 })48 defChannelId = config ? config.defaultPollChannel : ''49 if (defChannelId === '') { //Let's get the channel set up50 await channel.send(new Discord.MessageEmbed({51 title: 'Setup Your Default Channel',52 description: 'This will be where your polls are sent.\nSimply type in the name of your channel without mentioning it.',53 color: embedColor.LIGHT_GREEN54 })55 .addField('Cancel', `${prefix}cancel`)56 )57 await channel.awaitMessages(filter, { max: 1, time: defaultTimeout }).then(async collected => {58 const content = collected.first().content59 if (content.toLowerCase() === `${prefix}cancel`) {60 reply.replyExclaim(message, 'Canceled!')61 customCommands.removeUserToIgnore(message.author.id, 'CANCELED CREATE_POLL SEQ.')62 return63 }64 const foundChannel = message.guild.channels.cache.find(x => x.name === content)65 if (!foundChannel) {66 reply.replyExclaim(message, `Hmm... that channel doesn't seem to exist!`)67 customCommands.removeUserToIgnore(message.author.id, 'FAILED CREATE_POLL SEQ.')68 return69 }70 await channel.send(new Discord.MessageEmbed({71 title: 'Loading...',72 description: 'Hang on.',73 color: embedColor.CORNFLOWER_BLUE74 }))75 await mongo().then(async mongoose => {76 try {77 await guildConfigSchema.findOneAndUpdate({78 _id: guildId79 }, {80 _id: guildId,81 defaultPollChannel: foundChannel.id82 }, {83 upsert: true,84 useFindAndModify: false85 })86 defChannelId = foundChannel.id87 } finally {88 mongoose.connection.close()89 }90 })91 })92 } //At this point we should already have the channel set up93 let pollContent, duration = ''94 let emojis = []95 let enterEmoji = ''96 await channel.send(new Discord.MessageEmbed({97 title: 'Poll Content',98 description: 'What will your poll say?',99 color: embedColor.FRIENDLY_RED100 })101 .addField('Cancel', `${prefix}cancel`))102 await channel.awaitMessages(filter, { max: 1, time: defaultTimeout }).then(async collected => {103 const content = collected.first().content104 if (content.toLowerCase() === `${prefix}cancel`) {105 reply.replyExclaim(message, 'Canceled!')106 customCommands.removeUserToIgnore(message.author.id, 'CANCELED CREATE_POLL SEQ.')107 return108 }109 pollContent = content110 })111 if (isIncognito) {112 const enterEmojiEmbed = await channel.send(new Discord.MessageEmbed({113 title: 'Configure Your Enter Emoji',114 description: 'This will be the emoji members need to react with to enter the poll',115 color: embedColor.CORNFLOWER_BLUE116 })117 .addField('Cancel', `${prefix}cancel`)118 )119 await channel.awaitMessages(filter, { max: 1, time: defaultTimeout }).then(async collected => {120 const content = collected.first().content121 if (content.toLowerCase() === `${prefix}cancel`) { reply.replyExclaim(message, 'Canceled!'); customCommands.removeUserToIgnore(message.author.id, 'CANCELED CREATE_POLL SEQ.'); return }122 enterEmoji = content123 })124 }125 await channel.send(new Discord.MessageEmbed({126 title: 'Configure Your Reactions',127 description: 'These will be the reactions members can react with.\nType the emojis with spaces seperating them.\nExample: :white_check_mark: :thumbsup: :thumbsdown:',128 color: embedColor.LIGHT_GREEN129 }).addField('Cancel', `${prefix}cancel`))130 await channel.awaitMessages(filter, { max: 1, time: defaultTimeout }).then(async collected => {131 const content = collected.first().content132 if (content.toLowerCase() === `${prefix}cancel`) { reply.replyExclaim(message, 'Canceled!'); customCommands.removeUserToIgnore(message.author.id, 'CANCELED CREATE_POLL SEQ.'); return }133 const arr = content.split(' ')134 emojis = arr135 })136 await channel.send(new Discord.MessageEmbed({137 title: 'Configure Your Duration',138 description: 'How long will the poll last? e.g. 3d, 10s, 2w, 12h, etc.',139 color: embedColor.STREET_BLUE140 }))141 const numberRegex = /^\d+$/142 await channel.awaitMessages(filter, { max: 1, time: defaultTimeout }).then(async collected => {143 const content = collected.first().content.toLowerCase()144 if (content === `${prefix}cancel`) { reply.replyExclaim(message, 'Canceled!'); customCommands.removeUserToIgnore(message.author.id, 'CANCELED CREATE_POLL SEQ.'); return }145 const checkDuration = pollSystem.getEndTimestamp(content)146 if (!numberRegex.test(checkDuration)) {147 reply.replyExclaim(message, checkDuration)148 customCommands.removeUserToIgnore(message.author.id, 'FAILED CREATE_POLL SEQ.')149 return150 }151 duration = content152 })153 const defChannel = bot.getClient().channels.cache.get(defChannelId)154 if (!isIncognito) {155 pollSystem.addPoll(message, defChannel, emojis, pollContent, duration)156 }157 else {158 pollSystem.addIncognitoPoll(message, defChannel, emojis, enterEmoji, pollContent, duration)159 }160 customCommands.removeUserToIgnore(message.author.id, 'SUCCESS CREATE_POLL SEQ.')161 }...

Full Screen

Full Screen

isIncognito.js

Source:isIncognito.js Github

copy

Full Screen

...12 * Работает на основании факта, что в инкогнито режиме часть поддерживаемого браузарами API отключена.13 * <h2>Пример использования.</h2>14 * <pre>15 * require(['Core/detection/isIncognito'], function(isIncognito) {16 * isIncognito().then(function(enabled) {17 * console.log('Is incognito:', enabled);18 * }).catch(console.error);19 * });20 * </pre>21 *22 * @class Core/detection/isIncognito23 * @public24 * @author Мальцев А.А.25 */26 /**27 * Определяет, что браузер пользователя находится в инкогнито (приватном) режиме просмотра страниц.28 * <h2>Возвращает</h2>29 * {Promise.<Boolean>}30 * @remark31 * Работает на основании факта, что в инкогнито режиме часть поддерживаемого браузарами API отключена.32 * <h2>Пример использования.</h2>33 * <pre>34 * require(['Core/detection/isIncognito'], function(isIncognito) {35 * isIncognito().then(function(enabled) {36 * console.log('Is incognito:', enabled);37 * }).catch(console.error);38 * });39 * </pre>40 *41 * @class Core/detection/isIncognito42 * @public43 * @author Мальцев А.А.44 */45 function detectByRequestFileSystem(done, skip) {46 var requestFileSystem = window['RequestFileSystem'] || window['webkitRequestFileSystem'];47 if (!requestFileSystem) {48 return skip();49 }50 requestFileSystem(window['TEMPORARY'], 10, function () {51 done(false);52 }, function () {53 done(true);54 });55 }56 function detectByIndexedDB(done, skip) {57 if (window.indexedDB && detection.firefox) {58 var db;59 try {60 db = window.indexedDB.open('test');61 } catch (err) {62 return done(true);63 }64 return setTimeout(function () {65 if (db.readyState === 'done') {66 return done(!db.result);67 }68 skip();69 }, 300);70 } else if (detection.IEVersion >= 10) {71 try {72 if (!window.indexedDB) {73 return done(true);74 }75 } catch (err) {76 return done(true);77 }78 return done(false);79 }80 skip();81 }82 function detectByDB(done, skip) {83 if (!detection.safari) {84 skip();85 }86 try {87 window['openDatabase'](null, null, null, null);88 done(false);89 } catch (_) {90 done(true);91 }92 }93 function detectByNavigator(done, skip) {94 if (!detection.safari) {95 skip();96 }97 done(!navigator.doNotTrack);98 }99 function detectByLocalStorage(done, skip) {100 if (window.localStorage && detection.safari) {101 try {102 window.localStorage.setItem('test', '1');103 } catch (err) {104 return done(true);105 }106 window.localStorage.removeItem('test');107 return done(false);108 }109 skip();110 }111 function detect(done) {112 if (typeof window === 'undefined') {113 throw new Error('This feature available only in browser');114 }115 detectByRequestFileSystem(done, function () {116 detectByIndexedDB(done, function () {117 detectByDB(done, function () {118 detectByNavigator(done, function () {119 detectByLocalStorage(done, function () {120 throw new Error('Feature is not supported at this browser');121 });122 });123 });124 });125 });126 }127 function isIncognito() {128 return new Promise(function (resolve, reject) {129 try {130 detect(resolve);131 } catch (err) {132 reject(err);133 }134 });135 }136 exports.default = isIncognito;137 ;...

Full Screen

Full Screen

savetab.js

Source:savetab.js Github

copy

Full Screen

1// Copyright 2018 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4var saveTabs = document.getElementById('buttonDiv');5const otherBookmarksFolderId = "2";6const temporaryBookmarkFolderName = "暂存书签";7const windowPrefix = "window-";8const incognitoPrefix = "incognito-";9saveTabs.onclick = function () {10 getTemporaryBookmarkFolderId().then(getDateFolder).then(saveAllTabs);11};12function getTemporaryBookmarkFolderId() {13 var temporaryBookmarkFolderId = undefined;14 return new Promise(function (resolve) {15 chrome.bookmarks.getChildren(otherBookmarksFolderId, function (results) {16 for (var i = 0; i < results.length; i++) {17 if (results[i].title === temporaryBookmarkFolderName) {18 temporaryBookmarkFolderId = results[i].id;19 console.log("found temporary bookmark folder id: ", temporaryBookmarkFolderId);20 resolve(temporaryBookmarkFolderId);21 break;22 }23 }24 if (temporaryBookmarkFolderId === undefined) {25 createTemporaryBookmarkFolder().then(resolve);26 }27 });28 });29}30function createTemporaryBookmarkFolder() {31 return new Promise(function (resolve) {32 chrome.bookmarks.create({33 'parentId': otherBookmarksFolderId,34 'title': temporaryBookmarkFolderName35 }, function (result) {36 console.log("create temporary bookmark folder with id: ", result.id);37 resolve(result.id);38 });39 });40}41function getDateFolder(temporaryBookmarkFolderId) {42 var dateFolderId = undefined;43 return new Promise(function (resolve) {44 var dateString = formatDate(new Date());45 chrome.bookmarks.getChildren(temporaryBookmarkFolderId, function (results) {46 for (var i = 0; i < results.length; i++) {47 if (results[i].title === dateString) {48 dateFolderId = results[i].id;49 console.log("found date folder id: ", dateFolderId);50 resolve(dateFolderId);51 break;52 }53 }54 if (dateFolderId === undefined) {55 createDateFolder(temporaryBookmarkFolderId, dateString).then(resolve);56 }57 });58 })59}60function createDateFolder(temporaryBookmarkFolderId, dateString) {61 return new Promise(function (resolve) {62 chrome.bookmarks.create({63 'parentId': temporaryBookmarkFolderId,64 'title': dateString65 }, function (result) {66 console.log("create date folder with id: ", result.id);67 resolve(result.id);68 });69 });70}71function saveAllTabs(dateFolderId) {72 chrome.windows.getAll(function (windows) {73 saveAllTabsForDifferentWindowType(windows, dateFolderId, false);74 saveAllTabsForDifferentWindowType(windows, dateFolderId, true);75 });76}77function saveAllTabsForDifferentWindowType(windows, dateFolderId, isIncognito) {78 var windowIds = getWindowIds(windows, isIncognito);79 console.log("windowIds: ", windowIds);80 console.log("isIncognito: ", isIncognito);81 for (var i = 0; i < windowIds.length; i++) {82 createFolderForWindow(dateFolderId, windowIds[i], i, isIncognito).then(saveWindowTabs);83 }84}85function getWindowIds(windows, isIncognito) {86 return windows.filter(function (window) {87 return window.incognito === isIncognito;88 }).map(function (window) {89 return window.id;90 });91}92function createFolderForWindow(dateFolderId, windowId, i, isIncognito) {93 var windowFolderId = undefined;94 return new Promise(function (resolve) {95 chrome.bookmarks.create(96 {97 'parentId': dateFolderId,98 'title': (isIncognito ? incognitoPrefix : windowPrefix) + (i + 1)99 }, function (result) {100 windowFolderId = result.id;101 console.log("create window folder with id: ", windowFolderId);102 resolve([windowId, windowFolderId]);103 });104 });105}106function saveWindowTabs([windowId, windowFolderId]) {107 chrome.tabs.query({'windowId': windowId}, function (tabs) {108 tabs.forEach(function (tabItem) {109 chrome.tabs.get(tabItem.id, function (tab) {110 createBookmark(windowFolderId, tab);111 });112 });113 });114}115function createBookmark(windowFolderId, tab) {116 console.log("save bookmark for tab: ", tab.title);117 chrome.bookmarks.create(118 {119 'parentId': windowFolderId,120 'title': tab.title,121 'url': tab.url122 });...

Full Screen

Full Screen

background.js

Source:background.js Github

copy

Full Screen

1var maxCount,2 windowWidth,3 windowHeight,4 isIncognito,5 tweetLink = [],6 timeoutId,7 xhr = new XMLHttpRequest(),8 noop = function() {},9 allClear = function() {10 'use strict';11 for ( var j = 0; j < maxCount; j++ ) {12 chrome.notifications.clear( String(j), noop );13 }14 },15 setProperties = function() {16 'use strict';17 chrome.storage.local.get( 'tweet-notifier', function( items ) {18 var item = items['tweet-notifier'];19 maxCount = item.maxTweetVal;20 windowWidth = item.windowWidthVal;21 windowHeight = item.windowHeightVal;22 isIncognito = item.isIncognito;23 });24 },25 buttonClicked = {26 0: function() {27 'use strict';28 allClear();29 },30 1: function( notificationId ) {31 'use strict';32 chrome.windows.create(33 {34 url: tweetLink[Number( notificationId )],35 width: windowWidth,36 height: windowHeight,37 incognito: isIncognito38 },39 noop40 );41 chrome.notifications.clear( notificationId, noop );42 }43 };44xhr.responseType = 'document';45xhr.addEventListener( 'load', function() {46 'use strict';47 var tweetElements = this.response.querySelectorAll('div.original-tweet'),48 displayed = 0;49 for ( var i = 0; displayed < maxCount; i++ ) {50 var isRetweet = tweetElements[i].querySelector('.js-retweet-text'),51 icon = isRetweet ? '/images/retweet.jpg' : '/images/tweet.jpg',52 retweeter = isRetweet ? isRetweet.innerText : null,53 tweeter = tweetElements[i].dataset.name,54 tweetParagraph = tweetElements[i].querySelector('p.js-tweet-text.tweet-text'),55 tweet = tweetParagraph.innerText,56 buttonItems = [{ title: 'Clear' }];57 if ( tweetElements[i].querySelector('.js-action-profile-promoted') !== null ) {58 continue;59 }60 tweetLink[i] =61 tweetElements[i].querySelector('a.twitter-timeline-link') ?62 tweetElements[i].querySelector('a.twitter-timeline-link').href : null;63 if (tweetLink[i]) {64 buttonItems.push({title: tweetLink[i]});65 }66 chrome.notifications.create(67 String(i),68 {69 type: 'basic',70 iconUrl: icon,71 title: tweeter,72 message: tweet,73 contextMessage: retweeter,74 buttons: buttonItems,75 isClickable: true76 },77 noop78 );79 displayed++;80 }81});82chrome.browserAction.onClicked.addListener(function() {83 'use strict';84 setProperties();85 clearTimeout( timeoutId );86 allClear();87 xhr.open( 'GET', 'https://twitter.com/?lang=ja' );88 xhr.send();89 timeoutId = setTimeout( allClear, Math.floor( maxCount / 3 + 1 ) * 8000 );90});91chrome.notifications.onButtonClicked.addListener(function( notificationId, buttonIndex ) {92 'use strict';93 buttonClicked[buttonIndex]( notificationId );94});95chrome.notifications.onClicked.addListener(function( notificationId ) {96 'use strict';97 chrome.notifications.clear( notificationId, noop );98});99chrome.runtime.onInstalled.addListener(function() {100 'use strict';101 chrome.storage.local.get( 'tweet-notifier', function( items ) {102 if ( items['tweet-notifier'] === undefined ) {103 chrome.storage.local.set({104 'tweet-notifier': {105 'maxTweetVal': 5,106 'windowWidthVal': 500,107 'windowHeightVal': 400,108 'isIncognito': true109 }110 });111 }112 });...

Full Screen

Full Screen

incognito-check.js

Source:incognito-check.js Github

copy

Full Screen

...10 this.#appName = metadataProvider.getAppName();11 this.#siteIdentityProvider = siteIdentityProvider;12 }13 async run() {14 const isIncognito = await this.#siteIdentityProvider.isIncognito();15 if (isIncognito) {16 this.#states.running.enter({17 title: this.name,18 value: "Privates Fenster",19 details:20 `Soll ${this.#appName} trotzdem fortfahren?` +21 " Log‑Einträge können in der Konsole deines Browsers landen, und" +22 " das Backend kann Log‑Einträge auf dem Gerät hinterlassen." +23 " In den Logs können Namen besuchter Webseiten sichtbar sein." +24 " Wenn du trotzdem fortfahren möchtest, dann leere hinterher deine" +25 " Browser-Konsole und lösche die Logs im Backend.",26 icon: "warning",27 button: {28 name: "continue",...

Full Screen

Full Screen

user.reducer.js

Source:user.reducer.js Github

copy

Full Screen

1import { userActionTypes as $ } from "./user.types";2const INITIAL_STATE = {3 token: null,4 name: null,5 id: null,6 isLoading: false,7 isAuthenticated: false,8 isIncognito: false,9};10const userReducer = (state = INITIAL_STATE, action) => {11 switch (action.type) {12 case $.SKIP_AUTH:13 return {14 ...state,15 isIncognito: true,16 };17 case $.USER_LOADING:18 return {19 ...state,20 isLoading: true,21 };22 case $.USER_LOADED:23 return {24 ...state,25 isIncognito: false,26 isLoading: false,27 isAuthenticated: true,28 ...action.payload,29 };30 case $.LOAD_USER_FAIL:31 return {32 ...state,33 isLoading: false,34 };35 case $.AUTH_SUCCESS:36 return {37 ...state,38 isIncognito: false,39 isLoading: false,40 isAuthenticated: true,41 ...action.payload,42 };43 case $.CLEAR_USER_DATA:44 return {45 ...INITIAL_STATE,46 };47 default:48 return state;49 }50};...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import isIncognito from "./incognito";2import browser from "./browser";...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch();3 const page = await browser.newPage();4 const isIncognito = await page.browserContext().isIncognito();5 console.log(isIncognito);6 await browser.close();7})();8### launch([options])9(async () => {10 const browser = await puppeteer.launch();11 await browser.close();12})();13### newPage()14(async () => {15 const browser = await puppeteer.launch();16 const page = await browser.newPage();17 await browser.close();18})();19### page.goto(url[, options])20(async () => {21 const browser = await puppeteer.launch();22 const page = await browser.newPage();23 await browser.close();24})();25### page.screenshot([options])26(async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 await page.screenshot({ path: "screenshot.png" });30 await browser.close();31})();32### page.pdf([options])33(async () => {34 const browser = await puppeteer.launch();35 const page = await browser.newPage();36 await page.pdf({ path: "screenshot.pdf" });37 await browser.close();38})();39### page.evaluate(pageFunction[, ...args])

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch({ headless: false });3 const page = await browser.newPage();4 const incognitoContext = await browser.createIncognitoBrowserContext();5 const incognitoPage = await incognitoContext.newPage();6 const isIncognito = await incognitoPage.browserContext().isIncognito();7 console.log('Is Incognito: ' + isIncognito);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch({ headless: false });3 const page = await browser.newPage();4 const isIncognito = await page.browserContext().isIncognito();5 console.log(isIncognito);6 await browser.close();7})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 const incognitoContext = browser.defaultBrowserContext();7 const incognito = await incognitoContext.newPage();8 console.log(await incognito.isIncognito());9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch({14 });15 const page = await browser.newPage();16 const incognitoContext = browser.defaultBrowserContext();17 const incognito = await incognitoContext.newPage();18 await incognito.bringToFront();19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch({24 });25 const page = await browser.newPage();26 await page.emulate({27 viewport: {28 },29 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const isIncognito = await page.browserContext().isIncognito();6 console.log(isIncognito);7 await browser.close();8})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({ headless: false });4 const page = await browser.newPage();5 const incognito = await page.browserContext().isIncognito();6 console.log(incognito);7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch({ headless: false });12 const context = await browser.createIncognitoBrowserContext();13 const page = await context.newPage();14 const incognito = await page.browserContext().isIncognito();15 console.log(incognito);16 await browser.close();17})();18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch({ headless: false });21 const context = await browser.createIncognitoBrowserContext();22 const page = await context.newPage();23 const incognito = await page.browserContext().isIncognito();24 console.log(incognito);25 await browser.close();26})();27const puppeteer = require('puppeteer');28(async () => {29 const browser = await puppeteer.launch({ headless: false });30 const context = await browser.createIncognitoBrowserContext();31 const page = await context.newPage();32 const incognito = await page.browserContext().isIncognito();33 console.log(incognito);34 await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch({ headless: false });39 const context = await browser.createIncognitoBrowserContext();40 const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 let incognito = await page.browserContext().isIncognito();6 console.log(incognito);7 await browser.close();8})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await puppeteer.launch({3 });4 const page = await browser.newPage();5 const context = browser.defaultBrowserContext();6 await page.waitForSelector("button[aria-label='Your location']");7 await page.click("button[aria-label='Your location']");8 await page.waitForTimeout(3000);9 const incognito = await page.browserContext().isIncognito();10 console.log(incognito);11 await browser.close();12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 console.log(await page.browserContext().isIncognito());6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const context = await browser.createIncognitoBrowserContext();12 const page = await context.newPage();13 console.log(await page.browserContext().isIncognito());14 await browser.close();15})();16const puppeteer = require('puppeteer');17(async () => {18 const browser = await puppeteer.launch();19 const context = await browser.createIncognitoBrowserContext();20 const page = await context.newPage();21 console.log(await page.browserContext().isIncognito());22 await browser.close();23})();24const puppeteer = require('puppeteer');25(async () => {26 const browser = await puppeteer.launch();27 const context = await browser.createIncognitoBrowserContext();28 const page = await context.newPage();29 console.log(await page.browserContext().isIncognito());30 await browser.close();31})();32const puppeteer = require('puppeteer');33(async () => {34 const browser = await puppeteer.launch();35 const context = await browser.createIncognitoBrowserContext();36 const page = await context.newPage();37 console.log(await page.browserContext().isIncognito());38 await browser.close();39})();40const puppeteer = require('puppeteer');41(async () => {42 const browser = await puppeteer.launch();43 const context = await browser.createIncognitoBrowserContext();44 const page = await context.newPage();45 console.log(await page.browserContext().isIncognito());46 await browser.close();47})();48const puppeteer = require('p

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

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