How do websites code those "What Character Are You" Facebook links? - javascript

Here is an example of what I am referring to: Facebook Example
I don't understand how this is coded. Is it simply some code that states if your name begins with the letter "A" then you are this person, "B" then this person, etc... or is it more complex then that. I have seen people whose names both begin with "A" get different results, so could it be just a random result? And how would this all be coded on the website's end, since Facebook just pulls up an image/text preview of the site (which is also another question, how could so many "sites/name" exist for every name possible)
Any insight would be greatly appreciated!

There is many different ways this could be achieved but if you were speaking generally I would assume they where chosen at random for either an object, array, database etc. An example of this would be the following using a JavaScript array
const la = ["Goofy", "Bugs Bunny", "Yosemite Sam", "Porky Pig"]
const generateRandomCharacter = () => {
return `Your character is: ${la[Math.floor((Math.random() * la.length} + 0)]}`)
}
alert(generateRandomCharacter) /* would return your random character */
running the generateRandomCharacter would return your random character.
Again this could be achieved many other ways this is just an example.
For your question about 'how that many sites could exist' well from my very minimal experience with php I create a site that would write a new file each time a user loaded. I speculate that whenever you were to click the button to generate your character it was writing a file with your randomly chosen character and your facebook name as the filename but again my php knowledge is very minimal.
Hope this helped somehow.

Related

Obfuscate email address to hide from scrapers?

I want to hide my personal data (email and phone) from scrapers and bots. This data is in the href of anchor tags. Of course, actual users should still be able to have functional clickable links.
I was thinking to use a simple JavaScript function to encrypt and decrypt the data so that patterns matchers (*#*.* etc) who only get the HTML code won't find the actual email address.
So my encryption function is to convert the string to a list of character codes, incrementing all list elements by 1, and converting it back to a string. See below for the code.
My question: Is this an adequate way to hide data from scrapers? Or does every scraper render JS nowadays?
The code:
JSFiddle
function stringToCharCodes(string) {
// Returns a list of the character codes of a string
return [...string].map(c => c.charCodeAt(0))
}
function deobfuscate(obfString) {
// String to character codes
let obfCharCodes = stringToCharCodes(obfString);
// Deobfuscate function (-1)
let deobfCharCodes = obfCharCodes.map(e => e -= 1);
// Character codes back to string
// Use spread operator ...
return String.fromCharCode(...deobfCharCodes);
}
// Result of obfuscate("example#example.com")
let obfEmail = "fybnqmfAfybnqmf/dpn";
document.getElementById("email").href = "mailto:" + deobfuscate(obfEmail);
// Result of obfuscate("31612345678")
let obfPhone = "42723456789";
document.getElementById("whatsapp").href = "https://wa.me/" + deobfuscate(obfPhone);
function obfuscate(string) {
// Obfuscate - Use developer tools F12 to run this once and then use the obfuscated string in your website
// String to character codes
let charCodes = stringToCharCodes(string);
// Obfuscate function (+1)
let obfCharCodes = charCodes.map(e => e += 1);
// Character codes back to string
// Use spread operator ...
return String.fromCharCode(...obfCharCodes);
}
<h1>Obfuscate Email And Phone</h1>
<p>Scrapers without Javascript will not be able to harvest your personal data.</p>
<ul>
<li><a id="email">Mail</a></li>
<li><a id="whatsapp">WhatsApp</a></li>
</ul>
The question is hard to answer, because there is no absolute truth, but let me try it.
You'll never get your email hidden 100% securely. Anything that renders the email address in a way that the user can read it, can also be rendered by sophisticated email scraper programs.
Once we accept that, what remains is the challenge to find a reasonable balance between the effort to hide the email address and the damage caused by a scraped email address.
In my experience, obfuscating the email and the href=mailto tag using html character encoding for a few characters is extremely simple but still effective in most cases. In addition to that, it renders without Javascript.
Example:
peter.pan#neverland.org
may become something like
peter.pan#neverland.de
It's supposedly even enough to hide the mailto: and the #.
I would guess that, because there are so many email addresses that can be collected too easily, email scrapers don't tend to use a lot of highly sophisticated techniques for that purpose. It's just not necessary.
Remember, however good you try to hide your email address on a publicly accessible website, if it's in one of the many address leakages, you've lost anyway. I use custom email addresses for different services, and only for those services, and still I get spam sent to some of these addresses, so I'm sure they were leaked in some way.
With regard to your approach, I'd say yes, it's good enough.

DiscordJS: Check if input is in a string

Hello!
I will try to do my best as possible to explain this issue i have.
A bin with some of the code mentioned, with comments:
Codebin
I am currently working on a Discord bot, where there is data stored in a .json file (As string).
Maybe this should be converted to an array instead?
A user writes a command and the bot initializes a sequence where it will go through several options depending on whats found in the string.
I've been struggling with this far too long (atleast 10 hours now & i am severely out of ideas now) on getting a check in for user response, to see if the input he does is in the array.
If i write !color 76561197458345 - it starts the process as seen below:
As you see the Available Options for found Dino (Carnotaurus) is:
[Utah1, Utah2]
Which is correct since its listed as the detailcrest options for Carnotaurus below in my json
[
{
"name": "Acrocanthosaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
},
{
"name": "Carnotaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
}
]
What then happens is that the user is gonna give a input based on the options found (This case Utah1, Utah2).
I want the bot to check the response from user in chat, if his answer is existing in the json file.
If respond to the bot in chat with Utah1 - it would proceed to next question (Because it exists).
If respond to the bot in chat with Pizza2 - it would respond (Not found, please select available options)
TL;DR:
I simply need a way to check if user response (word) is existing in the string
If Yes: continue, If No: error
I hope someone can give tips, or atleast push in the right direction on how to procceed with this.
I found a simple, but obviously not the most smart answer to my own solution - however it works as expected.
I've changed my .json strings to simply not include any brackets
"detailcrest": "Utah1, Utah2",
To search through my string i applied a .split() function (to seperate words with ,)
const inputCheck = color.detailcrest.toLowerCase().split(',').includes(detailcrest);
If i then do a if else statement on it, it returns true or false - for the given input, if it exists in the json file.
if (inputCheck === true) {
console.log("found")
} else {
console.log("False")
}
Obviously this wouldn't be the smartest way to proceed in a professional
But in my little bot it should work out with what is expected.
Due to limits, i will accept my own answer as solution in two days.

Randomise next word with no duplicate in Hangman game using JavaScript

I have made a Hangman game using JavaScript. It works just fine, but I've found that every time I click on 'New Word' to start a new game, it's completely random (which is good), but it doesn't take into account whether or not the new word has already occurred/been played. So you get a lot of duplicates from previous words.
I have made about 50 words/answers that can appear. I just want it so that every time I click on 'New Word', it generates a new word (from my choices) at random, and doesn't ever duplicate the same word again, unless all other options/words have been played already.
For some reason this text box isn't putting all my code into a block, so to make things easier to read, this is a link to my code in Github. I've attached all files but I'm pretty sure you only need to look at my JavaScript code:
HTML:
https://raw.githubusercontent.com/kaw31/hangman/master/hangman.html
CSS: (I've commented out a bit of code from a previous version so just ignore that);
https://raw.githubusercontent.com/kaw31/hangman/master/css/style.css
JavaScript:
https://raw.githubusercontent.com/kaw31/hangman/master/js/script.js
Any help is much appreciated.
There are a couple of logic errors in your code:
The list of your categories is set every time you run play function - and for every game it's the same (that's why it's possible to retrieve a word that was retrieved in previous games), while it should be set once for given browser refresh. Therefore you should move categories to the top (var categories = [list of your categories]) so that it's persistent.
You're not removing the chosen word after it has been retrieved from the list of your words - that's why it'll still be available to be retrieved again even with above fix. To do so, you first should get the index of category and word and simply remove it:
var category_index = Math.floor(Math.random() * categories.length);
var word_index = Math.floor(Math.random() * categories[category_index].length;
categories[category_index] = categories[category_index].splice(word_index, 1);
Of course at that point, you'll also have to remove hints and cater for the situation when list of words is empty (both - for each category, and empty at all)
Personally, I'd change how your words are stored, instead of using multiple arrays, use object as such:
var categories = [{
title: "Sport Teams",
words: [{
word: "ARSENAL",
hint: "Thierry Henry",
}, ...
]}, ...
]
so, when retrieving a word, you're retrieving all information regarding it - at that point the list of words becomes more manageable and manipulation becomes a bit easier.

Reference management with HTML/CSS/Javascript (BibTeX style)

HTML+CSS+Javascript tools offer a great way to create beautiful presentations (e.g. reveal.js + MathJax). However, I usually need to add citations to my presentations, and I would like to do that in a systematic way (so the bibliography is organized and the references are well-formatted). This is something that get's handled quite easily in LaTeX through BibTeX.
The best solution I've found so far comes from a library called bibtex-js. It seems to do a good job on rendering BiBTeX files in HTML as a bibliography listing, which is partially what I want. However, I don't only need to render bibliography listings, but also, I need to refer to entries in that bibliography by some index, and get a uniformly formatted reference marker. Take, for example, how LaTeX usually handles this problem:
%In thebibliography.bib
#article{darwin1859origins,
title={On the origins of species by means of natural selection},
author={Darwin, Charles},
journal={London: Murray},
year={1859}
}
%In mydocument.tex
As \cite{darwin1859origins} sustains in his ground-breaking book...
The previous code would be rendered as something like "As Darwin(1859) sustains in his ground-breaking book". Moreover, the formatting in which the citation is rendered could also be customizable (e.g. "Darwin,1859", "(Darwing,1859)", "[DWN59]", "[1]", etc.).
So the question is, how do you handle a similar task on a HTML document?
Thank you all in advance!
Yes, there is an emacs extension called org-mode, which is text processing with a markdown like syntax.
This can export to reveal-js trough this: https://github.com/yjwen/org-reveal
Or in my case I use the spacemacs extension: https://github.com/syl20bnr/spacemacs/tree/master/layers/%2Bemacs/org#revealjs-support
So org mode is an intermediate format that compiles to whatever you want, ie reveal-js, html, or even latex.
This includes a reference management system: https://github.com/jkitchin/org-ref
I'm unhappy with this for reveal.js, if we use this with reveal.js we end up having all the citation being presented as the link (whatever we type after cite:) and the full format citations are grouped on whatever slide you place them (so if you have more than 3 you can't read it correctly, although I guess its in the HTML). What I want is either the numbers I get in latex or footnote based citations, because in case of slides footnotes work kind off good.
This will of course work for just HTML pages, however you probably want to have presentations like me. I was searching for a solution for this when I stumbled upon this unanswered question so I guess here is your answer.
I made a project, incidentally also called bibtex-js. Available on npm.
I made it because most BibTeX parsers out there take considerable shortcuts in parsing. This one aligns closely with the authoritative document on BibTeX, Tame the BeaST and so works pretty well in terms of references and parsing author names, which seems what you are after.
I would say, based on some bibliographic standard, roll your own inline citation function:
import {parseBibFile, normalizeFieldValue} from "bibtex";
// Parse bib file
const bibFile = parseBibFile(bibtexString); // insert the darwin1859origins example as a string
// Sanity check: print all ids of entries in the bibfile
console.log(Object.keys(bibFile.entries$));
// Get the entry we are after
const entry = bibFile.getEntry("darwin1859origins");
// Get the relevant fields
// normalizeFieldValue turns a BibTeX string into a Javascript string
const year = normalizeFieldValue(entry.getField("year"));
// get first author
// "author" is a special kind of BibTeX field
const author = entry.getField("author").authors$[0];
function inlineCite(author){
return "("
+ (author.firstNames
.concat(author.vons)
.concat(author.lastNames)
.concat(author.jrs)).join(" ")
+ "," + year
+ ")";
}
console.log(inlineCite(author)); // (Charles Darwin, 1859)
You can do something complicated with et al. if you have multiple authors.

Remove prefix with unknown characters in JavaScript

I have a web page that the title is changed from 'Pagename' to '(1) Pagename' when there is an update on the page. That number increments to 50 each time there is a new update and then is maxed out showing '(50+) Timeline'.
When logging page views, Google Analytics shows the '(n) Pagename', which I don't want. So I found out how to manually change to logged page title, _gaq.push(["_set", "title", 'new title']);.
So my question is, how do I most efficiently remove the (1-50)/(50+) prefix and just get 'Pagename'? Is regex best for this?
This is what I'm using based on the answer from Ross:
var window_title = window.title.replace(/^\(\d+\+?\)\s/, '');
_gaq.push(["_set", "title", window_title]);
Yes, RegEx can do that.
window.title.replace(/^\(\d+\+?\)\s/, '');
Of course it depends on what software your site is using as perhaps it would be possible to just output the page title without that prefix in the relevant part of the template. So echoing that directly into the Google Analytics tag. But I think the above javascript is probably the easier solution to implement.

Categories

Resources