Skip to content

Instantly share code, notes, and snippets.

@CatalanCabbage
Created February 15, 2024 06:46
Show Gist options
  • Save CatalanCabbage/1aba67625700f5747a6eb8489e595d42 to your computer and use it in GitHub Desktop.
Save CatalanCabbage/1aba67625700f5747a6eb8489e595d42 to your computer and use it in GitHub Desktop.
WIP, about you component that gets data from your browser and eerily shows your data
import React, {useEffect, useRef, useState} from 'react';
import './About.css';
let textOptions = {
cookieEnabled: {
true: '',
false: 'You\'ve turned cookies off? Wow. ',
}, platform: {
win: 'Chillin\' on your Windows'
}, deviceMemory : {
lowMemory: 'Your device has enough power to run DOOM, which is cool. ',
mediumMemory: 'Your device has enough power to run Road Rash, which is cool. ',
highMemory: 'Your device has enough power to run GTA Vice City, which is cool. ',
hugeMemory: 'Your device can probably run Crysis4, some insane RAM you got there. '
}, screenSize : {
mobile : {
small: 'But not on this tiny screen...',
large: 'You\'ve got a big screen for a phone too, so maybe it isn\'t impossible? '
}, computer: {
small: 'Maybe you should get a bigger screen though...',
medium: 'The screen is a good size too. ',
large: 'On your nice large monitor. '
}
}, browser: {
chrome: 'You can play it online too, but I think your Chrome needs an update. ',
firefox: 'I can see you\'re a Firefox person. Good vibes. But I think you need an update? ',
safari: 'Safari. So close to Chrome, but yet so far. ',
explorer: 'Internet explorer?! You\'re making me nostalgic. ',
opera: 'Good old Oprah. Or Opera? How do you spell it? '
}, language: {
english: 'First off - good thing we both speak English. ',
nonEnglish: 'Ah, never got to it, but always wanted to learn '
}, os: {
windows: 'Speaking of updates...I have a feeling Windows will restart your machine any time now.',
other: 'Oh wait. Forget it the game doesn\'t run on '
}, time: {
sunrise: 'Good morning early riser! Great time to watch the sunrise.',
morning: 'Good morning there!',
afternoon: 'Good afternoon!',
evening: 'Good evening!',
sunset: 'Good evening! Great time to watch the sunset.',
night: 'Hi there! It\'s late, not sleepy yet?',
lateNight: 'Hi there, you nocturnal animal!'
}
}
function isCookiesEnabled() {
let cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled === 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') !== -1) ? true : false;
}
return cookieEnabled;
}
function getAboutYouText() {
let aboutYouText = '';
let hour = new Date().getHours();
if (hour < 5) {
aboutYouText += textOptions.time.lateNight;
} else if (hour < 7) {
aboutYouText += textOptions.time.sunrise;
} else if (hour < 11) {
aboutYouText += textOptions.time.morning;
} else if (hour < 16) {
aboutYouText += textOptions.time.afternoon;
} else if (hour < 18) {
aboutYouText += textOptions.time.evening;
} else if (hour < 19) {
aboutYouText += textOptions.time.sunset;
} else if (hour < 21) {
aboutYouText += textOptions.time.evening;
} else {
aboutYouText += textOptions.time.night;
}
aboutYouText += '\n';
let language = getLanguage();
if (language) {
if (language.toLowerCase().indexOf('english') < 0) {
aboutYouText += textOptions.language.nonEnglish + language + '.';
} else {
aboutYouText += textOptions.language.english;
}
}
aboutYouText += '\n';
if (isCookiesEnabled()) {
aboutYouText += textOptions.cookieEnabled[isCookiesEnabled() + ''];
}
aboutYouText += '\n';
let deviceText = '';
let deviceMemory = getDeviceMemory() || 8;
let isMobileDevice = isMobile();
if (isMobileDevice == null) {
isMobileDevice = true;
}
if (deviceMemory) {
if (deviceMemory < 4) {
deviceText += textOptions.deviceMemory.lowMemory;
} else if (deviceMemory < 8) {
deviceText += textOptions.deviceMemory.mediumMemory;
} else if (deviceMemory < 16) {
deviceText += textOptions.deviceMemory.highMemory;
} else {
deviceText += textOptions.deviceMemory.hugeMemory;
}
//Replace text with mobile context
deviceText = deviceText.replace('device', isMobileDevice ? 'mobile' : 'computer');
aboutYouText += deviceText;
}
let screenSize = getScreenSize();
if (screenSize && screenSize.width) {
if (isMobileDevice) {
//Small mobile screen
if (screenSize.width < 350) {
aboutYouText += textOptions.screenSize.mobile.small;
} else {
aboutYouText += textOptions.screenSize.mobile.large;
}
} else {
if (screenSize.width < 650) {
aboutYouText += textOptions.screenSize.computer.small;
} else if (screenSize.width < 1300) {
aboutYouText += textOptions.screenSize.computer.medium;
} else {
aboutYouText += textOptions.screenSize.computer.large;
}
}
}
aboutYouText += '\n';
let browser = getBrowser();
if (browser != null && browser.browser != null) {
let browserLowerCase = browser.browser.toLowerCase();
if (browserLowerCase.indexOf('chrome') >= 0) {
aboutYouText += textOptions.browser.chrome;
} else if (browserLowerCase.indexOf('firefox') >= 0) {
aboutYouText += textOptions.browser.firefox;
} else if (browserLowerCase.indexOf('safari') >= 0) {
aboutYouText += textOptions.browser.safari;
} else if (browserLowerCase.indexOf('explorer') >= 0) {
aboutYouText += textOptions.browser.explorer;
} else if (browserLowerCase.indexOf('opera') >= 0) {
aboutYouText += textOptions.browser.opera;
} else {
aboutYouText += 'Is this really ' + browser.browser + '? Haven\'t seen this around in a while! ';
}
}
let os = getOS();
if (os) {
aboutYouText += '\n';
if (os.toLowerCase().indexOf('windows') >= 0) {
aboutYouText += textOptions.os.windows;
} else {
aboutYouText += textOptions.os.other + os + '.';
}
}
return aboutYouText;
}
function getDeviceMemory() {
//Works on Chrome, not on FF
let nav: any = navigator;
console.log(`Memory: At least ${nav.deviceMemory} GB`);
return nav.deviceMemory;
}
function getScreenSize() {
//https://stackoverflow.com/a/21342122/12415069
let screenSize;
if (window.screen.width) {
let width = (window.screen.width) ? window.screen.width : '';
let height = (window.screen.height) ? window.screen.height : '';
screenSize = {width, height};
}
return screenSize;
}
function getBrowser() {
//https://stackoverflow.com/a/21342122/12415069
let nAgt = navigator.userAgent;
let browser = navigator.appName;
let version = '' + parseFloat(navigator.appVersion);
let verOffset, nameOffset, ix;
let majorVersion = parseInt(navigator.appVersion, 10);
// Opera
if ((verOffset = nAgt.indexOf('Opera')) !== -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) !== -1) {
version = nAgt.substring(verOffset + 8);
}
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) !== -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
//IE 11 no longer identifies itself as MS IE, so trap it
//http://stackoverflow.com/questions/17907445/how-to-detect-ie11
else if ((browser === 'Netscape') && (nAgt.indexOf('Trident/') !== -1)) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
if ((verOffset = nAgt.indexOf('rv:')) !== -1) {
version = nAgt.substring(verOffset + 3);
}
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) !== -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) !== -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) !== -1) {
version = nAgt.substring(verOffset + 8);
}
// Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
// at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
// No mention of chrome in the user agent string. However it does mention CriOS, which presumably
// can be keyed on to detect it.
if (nAgt.indexOf('CriOS') !== -1) {
//Chrome on iPad spoofing Safari...correct it.
browser = 'Chrome';
//Don't believe there is a way to grab the accurate version number, so leaving that for now.
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) !== -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() === browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) !== -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) !== -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) !== -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
return {browser, version};
}
function isMobile() {
let nVer = navigator.appVersion;
return /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
}
function getOS() {
let nAgt = navigator.userAgent || 'asd';
var os = 'unknown';
var clientStrings = [
{s:'Windows 3.11', r:/Win16/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows ME', r:/Windows ME/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Linux', r:/(Linux|X11)/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
let osVersion = 'unknown';
let nVer = navigator.appVersion;
if (/Windows/.test(os)) {
osVersion = (/Windows (.*)/.exec(os) || [])[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS X':
osVersion = (/Mac OS X (10[\\._\d]+)/.exec(nAgt) || [])[1];
break;
case 'Android':
osVersion = (/Android ([\\._\d]+)/.exec(nAgt) || [])[1];
break;
case 'iOS':
let extractedVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer) || [];
osVersion = extractedVersion[1] + '.' + extractedVersion[2] + '.' + (extractedVersion[3] || 0);
break;
}
return os + ', ' + osVersion;
}
function getLanguage() {
//https://stackoverflow.com/a/63101737/12415069
let languages = {"ab":"Abkhazian","aa":"Afar","af":"Afrikaans","ak":"Akan","sq":"Albanian","am":"Amharic","ar":"Arabic","an":"Aragonese","hy":"Armenian","as":"Assamese","av":"Avaric","ae":"Avestan","ay":"Aymara","az":"Azerbaijani","bm":"Bambara","ba":"Bashkir","eu":"Basque","be":"Belarusian","bn":"Bengali (Bangla)","bh":"Bihari","bi":"Bislama","bs":"Bosnian","br":"Breton","bg":"Bulgarian","my":"Burmese","ca":"Catalan","ch":"Chamorro","ce":"Chechen","ny":"Chichewa, Chewa, Nyanja","zh":"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)","cv":"Chuvash","kw":"Cornish","co":"Corsican","cr":"Cree","hr":"Croatian","cs":"Czech","da":"Danish","dv":"Divehi, Dhivehi, Maldivian","nl":"Dutch","dz":"Dzongkha","en":"English","eo":"Esperanto","et":"Estonian","ee":"Ewe","fo":"Faroese","fj":"Fijian","fi":"Finnish","fr":"French","ff":"Fula, Fulah, Pulaar, Pular","gl":"Galician","gd":"Gaelic (Scottish)","gv":"Manx","ka":"Georgian","de":"German","el":"Greek","kl":"Kalaallisut, Greenlandic","gn":"Guarani","gu":"Gujarati","ht":"Haitian Creole","ha":"Hausa","he":"Hebrew","hz":"Herero","hi":"Hindi","ho":"Hiri Motu","hu":"Hungarian","is":"Icelandic","io":"Ido","ig":"Igbo","id, in":"Indonesian","ia":"Interlingua","ie":"Interlingue","iu":"Inuktitut","ik":"Inupiak","ga":"Irish","it":"Italian","ja":"Japanese","jv":"Javanese","kn":"Kannada","kr":"Kanuri","ks":"Kashmiri","kk":"Kazakh","km":"Khmer","ki":"Kikuyu","rw":"Kinyarwanda (Rwanda)","rn":"Kirundi","ky":"Kyrgyz","kv":"Komi","kg":"Kongo","ko":"Korean","ku":"Kurdish","kj":"Kwanyama","lo":"Lao","la":"Latin","lv":"Latvian (Lettish)","li":"Limburgish ( Limburger)","ln":"Lingala","lt":"Lithuanian","lu":"Luga-Katanga","lg":"Luganda, Ganda","lb":"Luxembourgish","mk":"Macedonian","mg":"Malagasy","ms":"Malay","ml":"Malayalam","mt":"Maltese","mi":"Maori","mr":"Marathi","mh":"Marshallese","mo":"Moldavian","mn":"Mongolian","na":"Nauru","nv":"Navajo","ng":"Ndonga","nd":"Northern Ndebele","ne":"Nepali","no":"Norwegian","nb":"Norwegian bokmål","nn":"Norwegian nynorsk","ii":"Sichuan Yi","oc":"Occitan","oj":"Ojibwe","cu":"Old Church Slavonic, Old Bulgarian","or":"Oriya","om":"Oromo (Afaan Oromo)","os":"Ossetian","pi":"Pāli","ps":"Pashto, Pushto","fa":"Persian (Farsi)","pl":"Polish","pt":"Portuguese","pa":"Punjabi (Eastern)","qu":"Quechua","rm":"Romansh","ro":"Romanian","ru":"Russian","se":"Sami","sm":"Samoan","sg":"Sango","sa":"Sanskrit","sr":"Serbian","sh":"Serbo-Croatian","st":"Sesotho","tn":"Setswana","sn":"Shona","sd":"Sindhi","si":"Sinhalese","ss":"Swati","sk":"Slovak","sl":"Slovenian","so":"Somali","nr":"Southern Ndebele","es":"Spanish","su":"Sundanese","sw":"Swahili (Kiswahili)","sv":"Swedish","tl":"Tagalog","ty":"Tahitian","tg":"Tajik","ta":"Tamil","tt":"Tatar","te":"Telugu","th":"Thai","bo":"Tibetan","ti":"Tigrinya","to":"Tonga","ts":"Tsonga","tr":"Turkish","tk":"Turkmen","tw":"Twi","ug":"Uyghur","uk":"Ukrainian","ur":"Urdu","uz":"Uzbek","ve":"Venda","vi":"Vietnamese","vo":"Volapük","wa":"Wallon","cy":"Welsh","wo":"Wolof","fy":"Western Frisian","xh":"Xhosa","yi, ji":"Yiddish","yo":"Yoruba","za":"Zhuang, Chuang","zu":"Zulu"};
let browserLang = navigator.language.split('-')[0];
return languages[browserLang];
}
async function getIPData() {
let data: any = {};
let response = await fetch(`https://ipapi.co/json/`)
let jsonData = await response.text();
data = JSON.parse(jsonData);
let resultData = {
callingCode: data.country_calling_code,
city: data.city,
country: data.country_name,
currency: data.currency_name,
utcOffset: data.utc_offset
};
console.log(resultData);
return resultData;
}
function About() {
setTimeout(() => {
document.getElementById('aboutCard')?.scrollIntoView({behavior: 'smooth'});
}, 800)
let aboutYouText = getAboutYouText();
useEffect(() => {
// each useEffect can return a cleanup function
return () => {
componentIsMounted.current = false;
};
}, []);
let [ipData, setIPData] = useState("");
const componentIsMounted = useRef(true);
useEffect(() => {
async function fetchIPData() {
try {
let resultIPData: any = await getIPData();
console.log(resultIPData);
if (componentIsMounted.current) {
let ipDataText = '\n\n';
if (resultIPData.callingCode) {
ipDataText += 'Anyway, thanks for visiting! I\'m always open to feedback. \nI\'ll give you a call at ' + resultIPData.callingCode + '███████. ';
}
if (resultIPData.city) {
ipDataText += 'Or even visit you when I come to ' + resultIPData.city + '. ';
} else if (resultIPData.country) {
ipDataText += 'Or even visit you when I come to ' + resultIPData.country + '. ';
}
ipDataText += '\n';
if (resultIPData.currency) {
ipDataText += 'Drinks on me (capped at 1000 ' + resultIPData.currency.toLowerCase() + 's).';
}
setIPData(ipDataText);
}
} catch (err) {
console.error(err);
}
}
fetchIPData();
}, []);
return (
<div id="aboutCard">
<section id="about-you-container">
<h2>About you</h2><br/>
{/* Device, OS, Screen, location, time, incognito, browser, language, connection speed */}
{aboutYouText}
{`${ipData}`}
</section>
<section>
<h2>About me</h2><br/>
██████████████████████<br/>
████████████████████████████<br/>
██████████<br/>
<br/>
████████████<span className="redactedText"> redacted </span>█████████████<br/>
███████████████<br/>
███████████████████<br/>
<br/><br/>
<div id="contact">
<table>
<tbody>
<tr>
<th className="key">Contact:</th>
<th className="value">dav.is@zohomail.in</th>
</tr>
<tr>
<th className="key">Mobile:</th>
<th className="value">████████</th>
</tr>
</tbody>
</table>
</div>
</section>
</div>
);
}
export default About;
@CatalanCabbage
Copy link
Author

Shows info about the visitor on my website https://dvsj.in/about

Not currently live because I don't have time to make it cool enough :)

It shows different text based on various properties of the visitor. Eg: Low RAM mentions Road Rash and high RAM mentions Crysis 4, Windows OS mentions updates etc.

Looks something like this:
image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment