Skip to content

Instantly share code, notes, and snippets.

@mfakane
Last active February 23, 2023 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfakane/4f613a4de336861b057d660fa847b7f8 to your computer and use it in GitHub Desktop.
Save mfakane/4f613a4de336861b057d660fa847b7f8 to your computer and use it in GitHub Desktop.
User Script for generating email aliases
// ==UserScript==
// @name Generate random email address from placeholders
// @namespace https://github.com/mfakane
// @version 0.1
// @description Automatically replaces placeholders in email addresses during input. Intended to use with plus aliases (e.g. yourusernamehere+XXXX@gmail.com) or custom domains (e.g. HOSTNAME+XXXX@example.com)
// @author mfakane
// @match http://*/*
// @match https://*/*
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant none
// @updateURL https://gist.githubusercontent.com/mfakane/4f613a4de336861b057d660fa847b7f8/raw/replace-email-address-placeholders.js
// @downloadURL https://gist.githubusercontent.com/mfakane/4f613a4de336861b057d660fa847b7f8/raw/replace-email-address-placeholders.js
// @supportURL https://gist.github.com/mfakane/4f613a4de336861b057d660fa847b7f8
// ==/UserScript==
(function() {
'use strict';
const generateRandomString = (length) => {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return [...Array(length).keys()]
.map(x => chars[Math.floor(Math.random() * chars.length)])
.join("");
};
const replacements = [
{ pattern: /X+/g, replacer: x => generateRandomString(x.length) },
{ pattern: /HOSTNAME/g, replacer: x => location.hostname.replace(/^(www|login|auth|accounts?)\./, "") },
];
const generateAlias = (email, hostname) => {
const atIndex = email.indexOf("@");
const localPart = replacements.reduce(
(str, x) => str.replace(x.pattern, x.replacer),
email.slice(0, atIndex)
);
return `${localPart}@${email.slice(atIndex + 1)}`;
};
document.addEventListener("input", (e) => {
const target = e.target;
if (target.nodeName?.toLowerCase() !== "input") return;
const value = target.value;
if (typeof value === "string" &&
value.match(/^.+@.+\..+$/) &&
replacements.some(x => x.pattern.test(value))) {
target.value = generateAlias(value);
}
}, true);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment