How to use checkBrowser method in Cypress

Best JavaScript code snippet using cypress

webdonation.js

Source:webdonation.js Github

copy

Full Screen

...6    toBrowser = browser;7}else{8    toBrowser = chrome9}10function checkBrowser(){11    var google_chrome   = navigator.userAgent.indexOf('Chrome') > -1;12    var edge = (/Edge\/\d./i.test(navigator.userAgent))13    var firefox  = navigator.userAgent.indexOf('Firefox') > -1;14    var safari   = navigator.userAgent.indexOf("Safari") > -1;15    var opera    = navigator.userAgent.indexOf(' OPR/') > -1;16    var browserName;17    if ((google_chrome) && (safari)) safari = false;18      if((google_chrome) && (edge)){19          google_chrome = false;20      }21      if( (google_chrome) && (opera)) google_chrome = false;22      if (google_chrome){23        browserName = 'chrome';24      }else if(firefox){25        browserName = 'firefox';26      }else if(safari){27        browserName = 'safari';28      }else if (edge){29        browserName = 'edge';30      }else if (opera){31        browserName = 'opera';32      }33      return browserName;34}35toBrowser.runtime.onMessage.addListener(function(request, sender, sendResponse){36    if(request.message == 'getTubeRate'){37        //Utilities38        const getAmountToBuy = async (tubeAmount = '', amount = '', type, buyType = undefined,curr) => {39            const token = await getFirebaseToken();40            let currency=curr;41            const url = functionBaseURL + '/app/getFIATTUBEPrice?tubeAmount=' + tubeAmount + '&currency=' + currency + '&fiatAmount=' + amount42            sendGetRequest(url, token, function (user, response) {43                const result = JSON.parse(response);44                switch (type) {45                    case 'getTubes':46                        if ( buyType === 'buyWithCrypto'){47                            if(checkBrowser() == "chrome"){48                                sendResponse({message:result.tubeAmount.toFixed(8),token:result.token})49                            }50                            else{51                                chrome.tabs.query({active: true}, function (tab) {52                                    chrome.tabs.sendMessage(tab[0].id, {message:'getTubeValue',value:result.tubeAmount.toFixed(8),token:result.token,type:type});53                                });54                            }55                        }56                        else{57                            if(checkBrowser() == "chrome"){58                                sendResponse({message: result.tubeAmount.toFixed(2),token:result.token})59                            }60                            else{61                                chrome.tabs.query({active: true}, function (tab) {62                                    chrome.tabs.sendMessage(tab[0].id, {message:'getTubeValue',value:result.tubeAmount.toFixed(2),token:result.token,type:type});63                                });64                            }65                        }66                    break;67                    case 'getFiat':68                        if (buyType === 'creditCard') {69                            if(checkBrowser() == "chrome"){70                                sendResponse({message: applyFeeForPurchase(result.fiatAmount, 'getFiat'),token:result.token})71                            }72                            else{73                                chrome.tabs.query({active: true}, function (tab) {74                                    chrome.tabs.sendMessage(tab[0].id, {message:'getTubeValue',value:applyFeeForPurchase(result.fiatAmount, 'getFiat'),token:result.token,type:type});75                                });76                            }77                        }78                        else {79                            if ( buyType === 'buyWithCrypto'){80                                if(checkBrowser() == "chrome"){81                                    sendResponse({message: result.fiatAmount.toFixed(8),token:result.token})82                                }83                                else{84                                    chrome.tabs.query({active: true}, function (tab) {85                                        chrome.tabs.sendMessage(tab[0].id, {message:'getTubeValue',value:result.fiatAmount.toFixed(8),token:result.token,type:type});86                                    });87                                }88                            }89                            else{90                                if(checkBrowser() == "chrome"){91                                    sendResponse({message: result.fiatAmount.toFixed(2),token:result.token})92                                }93                                else{94                                    chrome.tabs.query({active: true}, function (tab) {95                                        chrome.tabs.sendMessage(tab[0].id, {message:'getTubeValue',value:result.fiatAmount.toFixed(2),token:result.token,type:type});96                                    });97                                }98                            }99                        }100                    break;101                }102            });103        }104        const applyFeeForPurchase = (total, type) => {105            const fee = 0.25;106            const transactionFee = ((total * 4.5) / 100);107            switch (type) {108                case 'getTubes':109                    return parseFloat(total - (fee + transactionFee)).toFixed(2);110                case 'getFiat':111                    return parseFloat(total + (fee + transactionFee)).toFixed(2);112            }113        }114        if(request.target=='getTubes'){115            getAmountToBuy(undefined,request.value,request.target,request.type,request.currency)116        }117        else if (request.target == 'getFiat'){118            getAmountToBuy(request.value,undefined,request.target,request.type,request.currency)119        }120    }121    if(request.message == 'getTubePrice'){122        //Utilities123        const getTubePrice = async ( amount = '',curr) => {124            const token = await getFirebaseToken();125            let currency=curr;126            let url127            if(checkBrowser() == "chrome"){128                url = functionBaseURL + '/app/getFIATTUBEPrice?tubeAmount=1&currency=' + currency + '&fiatAmount=' + amount129            }130            else{131                url = functionBaseURL + '/app/getFIATTUBEPrice?tubeAmount=1&currency=' + currency + '&fiatAmount='132            }133            sendGetRequest(url, token, function (user, response) {134                const result = JSON.parse(response);135                if(checkBrowser() == "chrome"){136                    sendResponse({value:result.fiatAmount,currency:currency})137                }138                else{139                    chrome.tabs.query({active: true}, function (tab) {140                        chrome.tabs.sendMessage(tab[0].id, {message:'getTubePrice',value:result.fiatAmount,currency:currency,amount:amount});141                    });142                }143            });144        }145        if(checkBrowser() == "chrome"){146            getTubePrice(undefined,request.currency)147        }148        else{149            getTubePrice(request.amount,request.currency)150        }151    }152    if(request.message == 'getFavCurrency'){153        if(checkBrowser() == 'chrome'){154            if(localStorage.getItem("currencySelected") != undefined){155                sendResponse({currency:localStorage.getItem("currencySelected")})156            }157            else{158                sendResponse({message:"USD"})159            }160        }161        else{162            chrome.tabs.query({active: true}, function (tab) {163                chrome.tabs.sendMessage(tab[0].id, {message:'favCur',currency: 'USD',amount:request.value});164            });165        }166    }167    if(request.message == 'getBuyTubeStatus'){168        const getBuyTubeStatus = async () => {169            try {170                const status = await firebaseXhr(functionBaseURL + '/app/buyTubesStatus');171                if (status.wire && status.wire.maintenance){172                    if(checkBrowser() == "chrome"){173                        sendResponse({disabled:['wire'],message:status.wire.message})174                    }175                    else{176                        chrome.tabs.query({active: true}, function (tab) {177                            chrome.tabs.sendMessage(tab[0].id, {disabled:['wire'],message:'getBuyTubeStatus',error:status.wire.message});178                        });179                    }180                }181                if (status.crypto && status.crypto.maintenance){182                    if(checkBrowser() == "chrome"){183                        sendResponse({disabled:['crypto'],message:status.crypto.message})184                    }185                    else{186                        chrome.tabs.query({active: true}, function (tab) {187                            chrome.tabs.sendMessage(tab[0].id, {disabled:['crypto'],message:'getBuyTubeStatus',error:status.crypto.message});188                        });189                    }190                }191                if (status.cc && status.cc.maintenance){192                    if(checkBrowser() == "chrome"){193                        sendResponse({disabled:['cc'],message:status.cc.message})194                    }195                    else{196                        chrome.tabs.query({active: true}, function (tab) {197                            chrome.tabs.sendMessage(tab[0].id, {disabled:['cc'],message:'getBuyTubeStatus',error:status.cc.message});198                        });199                    }200                }201            } catch (err) {202                console.error('getBuyTubeStatus Error', err);203                if(err == "Error: No current user to get token for!"){204                    if(checkBrowser() == "chrome"){205                        sendResponse({disabled:['token'],error:'token'})206                    }207                    else{208                        chrome.tabs.query({active: true}, function (tab) {209                            chrome.tabs.sendMessage(tab[0].id, {disabled:['token'],message:'getBuyTubeStatus',error:'token'});210                        });211                    }212                }213                else{214                    if(checkBrowser() == "chrome"){215                        sendResponse({disabled:['wire','cc','crypto'],message:'Impossible to get buy tube status'})216                    }217                    else{218                        chrome.tabs.query({active: true}, function (tab) {219                            chrome.tabs.sendMessage(tab[0].id, {disabled:['wire','cc','crypto'],message:'getBuyTubeStatus'});220                        });221                    }222                }223            }224        };225        getBuyTubeStatus()226    }227    if(request.message == 'createTransferOrder'){228        let createOrder = true;229        const checkUserHasPhone = async () => {230            const claims = await getFirebaseClaims();231            if ( !claims.hasPhone && !claims.verified){232                createOrder = false;233                chrome.tabs.query({active: true}, function (tab) {234                    chrome.tabs.sendMessage(tab[0].id, {message:'createTransferOrder',error:'unverified'});235                });236            }237        }238        checkUserHasPhone();239        function randomReferenceNumber(){240            return (Math.floor((Math.random() * 982451653) + 982451653).toString(36) + Date.now().toString(36)).toUpperCase();241        }242        if (createOrder === true) {243            const refNo='TUBE-'+randomReferenceNumber();244            firebase.auth().currentUser.getIdToken().then(function (token) {245                var params = {};246                params.referenceId = refNo247                params.tubeamount = request.tubeAmount248                params.amount = request.amount249                params.currency = request.currency250                params.tubeValue=null251                params.timeTube = Date.now();252                params.token = encodeURIComponent(request.purchaseData)253                const url = functionBaseURL + '/app/createOrderTransferNew';254                var data = 'data=' + encodeURIComponent(JSON.stringify(params));255                sendPostRequest(url, data, null, token, function (user, response) {256                    const resultOrder = JSON.parse(response);257                    if(checkBrowser() == "chrome"){258                        sendResponse({message:resultOrder,data:params})259                    }260                    else{261                        chrome.tabs.query({active: true}, function (tab) {262                            chrome.tabs.sendMessage(tab[0].id, {message:'createTransferOrder',data:params,result:resultOrder});263                        });264                    }265                });266            });267        } else {268            if(checkBrowser() == "chrome"){269                sendResponse({error:'phoneError'})270            }271            else{272                chrome.tabs.query({active: true}, function (tab) {273                    chrome.tabs.sendMessage(tab[0].id, {message:'createTransferOrder',error:'unverified'});274                });275            }276        }277    }278    if(request.message == 'createCryptoOrder'){279        const getCoinbaseCommerceData = async (data) => {280            try {281                const token = await getFirebaseToken();282                const url = functionBaseURL + '/app/createCharge?token=' + encodeURIComponent(data);283                sendGetRequest(url, token, function (user, response) {284                    const resultOrder = JSON.parse(response);285                    if (resultOrder.message == 'success') {286                        if(checkBrowser() == "chrome"){287                            sendResponse({message:resultOrder})288                        }289                        else{290                            chrome.tabs.query({active: true}, function (tab) {291                                chrome.tabs.sendMessage(tab[0].id, {message:'createCryptoOrder',data:resultOrder});292                            });293                        }294                    }295                });296            } catch (err) {297                sendResponse({error:err})298            }299        }300        getCoinbaseCommerceData(request.purchaseData)301    }302    if(request.message == 'buyWithCreditCard'){303        const startProcessBuyWithCC = async (dataCC) => {304            try {305                const token = await getFirebaseToken();306                let params = {};307                if (dataCC != null) {308                    params.data = dataCC309                    params.token = encodeURIComponent(request.purchaseData)310                }311                const url = functionBaseURL + '/app/buyWithCreditCard';312                var data = 'data=' + encodeURIComponent(JSON.stringify(params));313                sendPostRequest(url, data, null, token, function (user, response) {314                    const result = JSON.parse(response);315                    if(checkBrowser() == "chrome"){316                        sendResponse({message:result})317                    }318                    else{319                        chrome.tabs.query({active: true}, function (tab) {320                            chrome.tabs.sendMessage(tab[0].id, {message:'buyWithCreditCard',data:result});321                        });322                    }323                });324            } catch (err) {325                console.error('Error starting buy with cc process ', err);326            }327        }328        startProcessBuyWithCC(request.data)329    }330    if (request.message == 'sendDonation'){331    let walletAddress = request.wallet;332    let ammount = request.amount;333    let paymentId = request.paymentid;334    let reqUseToDonate = request.usertodonate;335    localStorage.setItem('userToDonate', reqUseToDonate)336    let platform = request.platform;337    localStorage.setItem('userPlatform', platform);338    let action = request.action;339    if( action == 'sendDonation'){340            if (firebase.auth().currentUser != null ){341                // // console.log('before get user security ', ammount)342                getUserSecurity(function(response){343                    // // console.log('get user security ==> ', response, ' ', ammount)344                    if(response == 'userHasSecurity')345                    {346                        // document.getElementById("donate-2fa-modal").style.display = 'block';347                        if (checkBrowser() == 'chrome'){348                            sendResponse({message: 'userHasSecurity'})349                        }else{350                            chrome.tabs.query({errorOnDonation: true, active: true}, function (tab) {351                                chrome.tabs.sendMessage(tab[0].id, {message: 'userHasSecurity'});352                            });353                        }354                    }355                    else if (response == 'userHasNoSecurity'){356                        new_send_coins(walletAddress, ammount, paymentId);357                    }358                });359            }else{360                if (checkBrowser() == 'chrome'){361                    sendResponse({message: 'userNotLoggedIn'})362                }else{363                    chrome.tabs.query({errorOnDonation: true, active: true}, function (tab) {364                        chrome.tabs.sendMessage(tab[0].id, {message: 'userNotLoggedIn'});365                    });366                }367            }368        }369    else if( action == 'verifyCode' ){370            let code = request.code;371            update2FAToken(code)372                .then(() => {373                    if (checkBrowser() == 'chrome'){374                        sendResponse({message: 'correctCode', error: 'The 2FA code is correct'})375                    }else{376                        chrome.tabs.query({errorOnDonation: true, active: true}, function (tab) {377                            chrome.tabs.sendMessage(tab[0].id, {message: 'correctCode', error: 'The 2FA code is correct'});378                        });379                    }380                })381                .catch(err => {382                    if (checkBrowser() == 'chrome'){383                        sendResponse({message: 'errorCode', error: err.message})384                    }else{385                        chrome.tabs.query({errorOnDonation: true, active: true}, function (tab) {386                            chrome.tabs.sendMessage(tab[0].id, {message: 'errorCode', error: err.message});387                        });388                    }389                });390    }391    else if (action == 'sendCoins'){392        new_send_coins(walletAddress, ammount, paymentId);393    }394    async function new_send_coins(walletAddress, ammount, paymentId){395        let token = await firebase.auth().currentUser.getIdToken();396        let wallets = await WalletHelpers.getWalletsInfo(token);397        var onlinewallet = wallets.onlinewallet;398        // let public_address = onlinewallet.public_addr;399        let public_address = cnUtil.pubkeys_to_string(onlinewallet.spend.pub, onlinewallet.view.pub);400        let pub_keys = {401        view: onlinewallet.view.pub,402        spend: onlinewallet.spend.pub403        }404        let sec_keys = {405        view: onlinewallet.view.sec,406        spend: onlinewallet.spend.sec407        }408        let login_success = await WalletHelpers.walletLogin(public_address, sec_keys.view);409        if(!login_success)410        {411            showDonationError('Something went wrong. Please try again');412            return;413        }414        let parsed_amount;415        console.log('Amount !! ==> ', ammount, '   ', typeof(ammount))416        try {417            parsed_amount = mymonero_core_js.monero_amount_format_utils.parseMoney(ammount);418        } catch (e) {419            showDonationError("Please enter a valid amount");420            return;421        }422        var params = {423            is_sweeping: false,424            payment_id_string: paymentId,//payId, // passed in425            sending_amount: parsed_amount.toString(), // sending amount426            from_address_string: public_address,427            sec_viewKey_string: sec_keys.view,428            sec_spendKey_string: sec_keys.spend,429            pub_spendKey_string: pub_keys.spend,430            to_address_string: walletAddress,431            priority: 1,432            unlock_time: 0, // unlock_time433            nettype: 0,434            get_unspent_outs_fn: function(req_params, cb)435            {436                WalletHelpers.getUnspentOuts(req_params, function(err_msg, res){437                    cb(err_msg, res);438                })439            },440            get_random_outs_fn: function(req_params, cb)441            {442                WalletHelpers.getRandomOuts(req_params, function(err_msg, res)443                {444                    cb(err_msg, res);445                });446            },447            submit_raw_tx_fn: function(req_params, cb)448            {449                WalletHelpers.submitRawTx(req_params, function(err_msg, res)450                {451                    cb(err_msg, res);452                });453            },454            status_update_fn: function(params)455            {456            },457            error_fn: function(params)458            {459                showDonationError(params.err_msg);460            },461            success_fn: async function(params)462            {463                const sent_tx = {464                    userSocialId: localStorage.getItem('userSocialId'),465                    userPlatorm: platform, //localStorage.getItem('userPlatform'),466                    username: reqUseToDonate, //localStorage.getItem('userToDonate'),467                    address: walletAddress,468                    amount: ammount,469                    paymentId: params.final_payment_id,470                    tx_hash: params.tx_hash,471                    tx_key: params.tx_prvkey,472                    tx_fee: params.used_fee473                };474                const data = {475                    suffix: 'donations',476                    type: 0,477                    data: sent_tx478                };479                showTransactionSent(sent_tx);480                await WalletHelpers.addHistory(token, data);481                // showHideButtonLoader('buttonConfirm', 'hideLoader');482            },483        }484        let blockchain_height = await WalletHelpers.getBlockchainHeight(public_address, sec_keys.view);485        if(!blockchain_height)486        {487            showDonationError('Failed to retrieve blockchain height please try again');488            return;489        }490        let coreBridge_instance = await mymonero_core_js.monero_utils_promise;491        // coreBridge_instance.set_current_blockchain_height(blockchain_height);492        coreBridge_instance.async__send_funds(params);493    }494    function getUserSecurity(callback)495        {496          firebase.auth().currentUser.getIdToken().then(function(token)497          {498            const url = functionBaseURL + '/app/getUserSecurity';499            sendGetRequest(url, token, function(user, response){500              try{501                if(callback)502                  callback(response);503              }504              catch(ex)505              {506                  //// console.log(ex);507                //// console.log(response);508              }509            });510          });511    }512    function verify2FASecret(secret, callback)513        {514          firebase.auth().currentUser.getIdToken().then(function(token)515          {516            const url = functionBaseURL + '/app/verifySecret?userToken='+secret+'&action=verifySecret';517            sendGetRequest(url, token, function(user, response){518              try{519                if(callback)520                  callback(response);521              }522              catch(ex)523              {524                //// console.log(response);525              }526            });527          });528    }529    function showTransactionSent(data_transaction){530        // console.log('SHOW TRANSACTION SENT');531        // console.log(data_transaction)532        if (checkBrowser() == 'chrome'){533            sendResponse({message: "donationSent", data: data_transaction});534        }else{535            chrome.tabs.query({currentWindow: true, active: true}, function (tab) {536                chrome.tabs.sendMessage(tab[0].id, {message: 'donationSent', data: data_transaction});537            });538        }539    }540    function showDonationError(error){541        // console.log('SHOW DONATION ERROR');542        // console.log(error)543        if (checkBrowser() == 'chrome'){544            sendResponse({message: "errorOnDonation", data: error});545        }else{546            chrome.tabs.query({currentWindow: true, active: true}, function (tab) {547                chrome.tabs.sendMessage(tab[0].id, {message: 'errorOnDonation', data: error});548            });549        }550    }551    }552    return true;...

Full Screen

Full Screen

browserCheck.js

Source:browserCheck.js Github

copy

Full Screen

1/**2 * https://hamonia.kr/3 */4// 브라우저 체크 - return boolean5function browserCheck(isAlert){6	7	var text = browserCheckReturnText();8	var msg = '하모니아는 크롬, 파이어폭스, 오페라, 사파리 브라우저로 이용하실 수 있습니다.';9	var checkBrowser = true;10	11	12	// 기기별 사용설정13	if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {14		15		// iOS safari 아닌 경우16		if(text != 'Safari'){17			msg = 'iOS는 사파리 브라우저로 이용하실 수 있습니다.';18			checkBrowser = false;19		}20		21		// iOS 버전 체크 - iOS 11.2  부터 WebRTC 지원22		var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);23		var ios_versions = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];24		var notProblemVersions = true;25		26		// 버전체크27		if(ios_versions[0] < 11) notProblemVersions = false;28		if(ios_versions[0] == 11 && ios_versions[1] < 2) notProblemVersions = false;29		30//		alert(ios_versions[0] + '.' + ios_versions[1]);	ex) 11.431		32		// 지원버전 이하인경우33		if( !notProblemVersions ){34			msg = 'iOS 11.2 이상에서 이용하실 수 있습니다.';35			checkBrowser = false;36		}37		38	}else if(/Android/i.test(navigator.userAgent)) {39		msg = '안드로이드는 크롬 브라우저로 이용하실 수 있습니다.';40		41		// android 브라우저별 사용여부 설정 - 주석 == 사용하는 브라우저42		if(text == 'kakaotalk'){ checkBrowser = false; }43		else if(text == 'Samsung')	{ checkBrowser = false; }44		else if(text == 'Ucbrowser'){ checkBrowser = false; }45		else if(text == 'Edge')		{ checkBrowser = false; }46		else if(text == 'OperaMini'){ checkBrowser = false; }47//		else if(text == 'Opera')	{ checkBrowser = false; }48//		else if(text == 'Chrome')	{ checkBrowser = false; }49		else if(text == 'Star Office'){ checkBrowser=false; }50		else if(text == 'WebTV')	{ checkBrowser = false; }51		else if(text == 'Beonex')	{ checkBrowser = false; }52		else if(text == 'Chimera')	{ checkBrowser = false; }53		else if(text == 'NetPositive'){ checkBrowser=false; }54		else if(text == 'Phoenix')	{ checkBrowser = false; }55		else if(text == 'Firefox')	{ checkBrowser = false; }56		else if(text == 'Safari')	{ checkBrowser = false; }57		else if(text == 'SkipStone'){ checkBrowser = false; }58		else if(text == 'Netscape')	{ checkBrowser = false; }59		else if(text == 'Mozilla')	{ checkBrowser = false; }60		else if(text == 'other')	{ checkBrowser = false; }61	}62	63	64	// PC 브라우저별 사용여부 설정 - 주석 == 사용하는 브라우저65	else if(text == 'Ie')		{ checkBrowser = false; }66	else if(text == 'kakaotalk'){ checkBrowser = false; }67	else if(text == 'Samsung')	{ checkBrowser = false; }68	else if(text == 'Ucbrowser'){ checkBrowser = false; }69	else if(text == 'Edge')		{ checkBrowser = false; }70	else if(text == 'OperaMini'){ checkBrowser = false; }71//	else if(text == 'Opera')	{ checkBrowser = false; }72//	else if(text == 'Chrome')	{ checkBrowser = false; }73	else if(text == 'Star Office'){ checkBrowser=false; }74	else if(text == 'WebTV')	{ checkBrowser = false; }75	else if(text == 'Beonex')	{ checkBrowser = false; }76	else if(text == 'Chimera')	{ checkBrowser = false; }77	else if(text == 'NetPositive'){ checkBrowser=false; }78	else if(text == 'Phoenix')	{ checkBrowser = false; }79//	else if(text == 'Firefox')	{ checkBrowser = false; }80//	else if(text == 'Safari')	{ checkBrowser = false; }81	else if(text == 'SkipStone'){ checkBrowser = false; }82	else if(text == 'Netscape')	{ checkBrowser = false; }83	else if(text == 'Mozilla')	{ checkBrowser = false; }84	else if(text == 'other')	{ checkBrowser = false; }85	86	87	if( !checkBrowser && isAlert ) alert(msg);88	89	return checkBrowser;90}91// 브라우저 체크 - return 브라우저명92function browserCheckReturnText(){93	var agt = navigator.userAgent.toLowerCase();94	var text = '';95	96	if ((navigator.appName == 'Netscape' && agt.indexOf('trident') != -1) 97			|| (agt.indexOf("msie") != -1)) 	text = 'Ie';98	else if (agt.indexOf("kakaotalk") != -1)	text = 'kakaotalk';99	else if (agt.indexOf("samsung") != -1)		text = 'Samsung';100	else if (agt.indexOf("ucbrowser") != -1)	text = 'Ucbrowser';101	else if (agt.indexOf("edge/") != -1)		text = 'Edge';102	else if (agt.indexOf("trident") != -1)		text = 'Trident';103//	else if (agt.indexOf("opr/") != -1)			text = 'OperaMini';	// 미적용 수정필요104	else if (agt.indexOf("opr/") != -1)			text = 'Opera';105	else if (agt.indexOf("chrome") != -1)		text = 'Chrome';106	else if (agt.indexOf("staroffice") != -1)	text = 'Star Office';107	else if (agt.indexOf("webtv") != -1)		text = 'WebTV';108	else if (agt.indexOf("beonex") != -1)		text = 'Beonex';109	else if (agt.indexOf("chimera") != -1)		text = 'Chimera';110	else if (agt.indexOf("netpositive") != -1)	text = 'NetPositive';111	else if (agt.indexOf("phoenix") != -1)		text = 'Phoenix';112	else if (agt.indexOf("firefox") != -1)		text = 'Firefox';113	else if (agt.indexOf("safari") != -1)		text = 'Safari';114	else if (agt.indexOf("skipstone") != -1)	text = 'SkipStone';115	else if (agt.indexOf("netscape") != -1)		text = 'Netscape';116	else if (agt.indexOf("mozilla/5.0") != -1)	text = 'Mozilla';117	else 										text = 'other';118	119//	alert('navigator.userAgent.toLowerCase() : ' + navigator.userAgent.toLowerCase() + '\n\nyour browser : ' + text);120//	alert('navigator.userAgent : ' + navigator.userAgent + '\n\nyour browser : ' + text); //other121//	alert('navigator.appName : ' + navigator.appName + '\n\nyour browser : ' + text); //ie122	123	return text;...

Full Screen

Full Screen

BsstWindow.js

Source:BsstWindow.js Github

copy

Full Screen

...35 		winJson['url'] = this.settings.linkFlag ? url : BSST.getWebAppPath() + url;36 		winJson['url'] = winJson['url'] + (winJson['url'].indexOf("?") > 0 ? '&' : '?' ) + 'winName=' + winJson['winName'];37 		winJson = BSST.unionJson(winJson, _this.settings);38 		39 		if(this.checkBrowser()) {40 			top.window.external.popupWinWithName(winJson['winName'], winJson['url'],41 			winJson['width'], winJson['height'] + 20, winJson['resizable']);42 		}43 		else {44 			var theLeft = (screen.width-winJson['width'])/2-2;45			var theTop = (screen.height-winJson['height'])/2;46			top.window.open(winJson['url'],winJson['winName'],47						'width=' + winJson['width'] + ',height=' + winJson['height'] + ',left=' + theLeft + ',top=' + theTop + ',' +48						'toolbar=0, location=0, menubar=0, scrollbars=0, resizable=0, status=0').focus();49 		}50 	},51 	52 	//检测是否专用浏览器(专用浏览器中包含window.external.version()方法)53 	this.checkBrowser = function(){54 		55 		try {56			if(top.window.external.version) {57				return true;58			}59		}catch(e){60			return false;61		}62 		63		return false;64 	}65 	66 	//关闭当前窗口67 	this.closePage = function(){68 		if(this.checkBrowser()) {69 			window.external.closePopupWin();70 		}71 		else {72 			window.close();73 		}74 	}75 	76 	//显示窗口77 	this.showMainWindow = function(flag) {78 		if(this.checkBrowser()) top.window.external.openMainWin(BSST.emptyValueEx(flag, true));79 	}80 	81 	//退出应用程序82 	this.exitPlatForm = function(){83 		if(this.checkBrowser()) top.window.external.exitPlatform();84 	}85 	86 	//调用弹出窗口事件事件87 	this.callPopWinScript = function(winName,callbackMethod){88 		if(this.checkBrowser()) top.window.external.callPopWinScript(winName,callbackMethod);89 	}90 	91 	//调用主窗口的事件92 	this.callMainFrameScript = function(callbackMethod){93 		if(this.checkBrowser()) top.window.external.callMainFrameScript(callbackMethod);94 	}95 	96	//调用主窗口的事件97 	this.callWorkFrameScript = function(json){98 		if(!this.checkBrowser()) return; 99 		json = BSST.emptyJson(json);100 		//如果不是主页时,调用工作区域的窗口101 		var workTop = BSST.emptyValueEx(json['isMainFrame'],0) == 1 ? "" : "top.mainframe.workspace.";102 		var jsonParam = typeof(json['param']) == 'object' ? BSST.covertToString(json['param']) : BSST.emptyValue(json['param']);103 		var jsonStr = "{callbackMethod:" + workTop +json['callbackMethod']+",param:" + jsonParam + "}";104 		top.window.external.callMainFrameMethod('callIndexMethod', jsonStr);105 	}
...

Full Screen

Full Screen

zeptoCommon.js

Source:zeptoCommon.js Github

copy

Full Screen

...58        return this.data[key];59    }60}61//移动端检查62function checkBrowser() {63    var u = navigator.userAgent.toLowerCase();64    if (u.indexOf('mobile') == -1 && u.indexOf('iphone') == -1) {65        window.location.href = "../error_browser.html";66    }67}68// 注册真实点击69function registerReallyClick($selector) {70    var falg = false;71    $selector.on('touchstart', function() {72        falg = false;73    });74    $selector.on('touchmove', function() {75        falg = true;76    });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import Vue from 'vue';2import VueRouter from 'vue-router';3import Lounge from '../views/Lounge';4import Store from '../store/index';5import Mobile from '../views/Mobile.vue';6import CheckPwd from '../views/CheckPwd.vue';7import CheckBrowser from '@/views/CheckBrowser.vue';8import loungeKey from '../../loungeKey';9Vue.use(VueRouter);10const routes = [11  {12    path: '/',13    name: 'Home',14    component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue'),15    meta: { unauthorized: true },16    beforeEnter: (to, from, next) => {17      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {18        next('/mobile');19      }20      next();21    },22  },23  {24    path: '/myPage',25    name: 'MyPage',26    component: () => import(/* webpackChunkName: "MyPage" */ '../views/MyPage.vue'),27  },28  {29    path: '/lounge',30    name: 'Lounge',31    component: Lounge,32    meta: { unauthorized: true, layout: 'MobileLayout' },33    beforeEnter: (to, from, next) => {34      if (to.query[loungeKey]) {35        next();36      } else {37        next('/checkPwd');38      }39    },40  },41  {42    path: '/search',43    name: 'Search',44    component: () => import(/* webpackChunkName: "Search" */ '../views/Search.vue'),45    meta: { unauthorized: true },46  },47  {48    path: '/playPage',49    name: 'PlayPage',50    component: () => import(/* webpackChunkName: "PlayPage" */ '../views/PlayPage.vue'),51    meta: { unauthorized: true },52  },53  {54    path: '/mobile',55    name: 'Mobile',56    component: Mobile,57    meta: { unauthorized: true, layout: 'MobileLayout' },58  },59  {60    path: '/checkPwd',61    name: 'checkPwd',62    component: CheckPwd,63    meta: { unauthorized: true, layout: 'MobileLayout' },64  },65  {66    path: '/checkBrowser',67    name: 'CheckBrowser',68    component: CheckBrowser,69    meta: { unauthorized: true, layout: 'MobileLayout' },70  },71  {72      path: '*',73      component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue'),74  },75]76const router = new VueRouter({77  mode: 'history',78  base: process.env.BASE_URL,79  routes,80  scrollBehavior () {81    return { x: 0, y: 0 }82  },83});84router.beforeEach((to, from, next) => {85  if (to.matched.some(record => record.meta.unauthorized) === false 86      && !Store.state.login.dealiName) {87        alert('로그인 해주세요.');88        return next('/');89  }90  const browse = navigator.userAgent.toLowerCase();91  if (browse.indexOf("chrome") === -1 && to.path !== '/checkBrowser') {92    return next('/checkBrowser');93  }94  95  return next();96});...

Full Screen

Full Screen

EditorFooter.js

Source:EditorFooter.js Github

copy

Full Screen

...8        super(props);9        this.$sourceInput = null;10        this.$digestTextarea = null;11        this.modal = new Modal({id: 'checkBrowserModal'});12        this.checkBrowser();13        this.rendered();14    }15    checkBrowser = () =>{16        this.modal.$body = new CheckBrowser({parent: this});17        let isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1;18        let isMobile = window.navigator.userAgent.indexOf("Mobile") !== -1;19        if(!isChrome && !isMobile && document.body.clientWidth>768){20            this.modal.open();21        }22    };23    rendered = () => {24        this.$sourceInput = this.find('.col-editor-footer-source input');25        this.$digestTextarea = this.find('.col-editor-footer-digest textarea');26    };...

Full Screen

Full Screen

winLocation.js

Source:winLocation.js Github

copy

Full Screen

...15        return this.data[key];16    }17}18//移动端检查19function checkBrowser() {20    var u = navigator.userAgent.toLowerCase();21    if (u.indexOf('mobile') == -1 && u.indexOf('iphone') == -1) {22        window.location.href = "../error_browser.html";23    }24}25function postAjax(url, param, callBack, asyncVal) {26    var av = asyncVal ? asyncVal : false;27    $.ajax({28        type: 'post',29        dataType: "json",30        url: url,31        data: param,32        cache: false,33        async: false,...

Full Screen

Full Screen

check-browser.js

Source:check-browser.js Github

copy

Full Screen

...30          }31          return scope.supported;32        };33        scope.$watch('required', function() {34          return checkBrowser();35        }, true);36        scope.$watch('required', function() {37          return checkBrowser();38        }, true);39      }40    };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2    it('Visits the Kitchen Sink', function() {3        cy.contains('type').click()4        cy.url().should('include', '/commands/actions')5        cy.get('.action-email')6            .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.checkBrowser()4    cy.contains('type').click()5    cy.url().should('include', '/commands/actions')6    cy.get('.action-email')7      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress');2const browser = cypress.checkBrowser();3const cypress = require('cypress');4const browser = cypress.checkBrowser();5const cypress = require('cypress');6const browser = cypress.checkBrowser();7const cypress = require('cypress');8const browser = cypress.checkBrowser();9const cypress = require('cypress');10const browser = cypress.checkBrowser();11const cypress = require('cypress');12const browser = cypress.checkBrowser();13const cypress = require('cypress');14const browser = cypress.checkBrowser();15const cypress = require('cypress');16const browser = cypress.checkBrowser();

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Browser Detection', () => {2    it('should detect Firefox browser', () => {3        cy.checkBrowser('firefox');4    })5    it('should detect Chrome browser', () => {6        cy.checkBrowser('chrome');7    })8    it('should detect Safari browser', () => {9        cy.checkBrowser('safari');10    })11    it('should detect Edge browser', () => {12        cy.checkBrowser('edge');13    })14})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Test", () => {2  it("should show a warning for old browsers", () => {3    cy.checkBrowser();4  });5});6Cypress.Commands.add("checkBrowser", () => {7  const browser = Cypress.browser;8  const browserName = browser.name;9  const browserVersion = browser.version;10  if (11    (browserName === "chrome" && browserVersion < 80) ||12    (browserName === "firefox" && browserVersion < 74) ||13    (browserName === "edge" && browserVersion < 80)14  ) {15    cy.log("Old browser detected");16    cy.on("window:alert", (str) => {17      expect(str).to.equal("Please upgrade your browser");18    });19  }20});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Browser compatibility', () => {2    it('Browser is compatible', () => {3        cy.checkBrowser({4        });5    });6});

Full Screen

Cypress Tutorial

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

Chapters:

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

Certification

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

YouTube

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

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful