-
-
Save jt-wang/f66017a67a80a75457020a82a01cff8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Type Guard | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description try to take over the world! | |
// @author Chuang Yu | |
// @match *://*/* | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=google.com | |
// @grant none | |
// ==/UserScript== | |
(function () { | |
"use strict"; | |
// Get all text boxs including inputs and textareas | |
const textboxes = document.querySelectorAll("input, textarea"); | |
function setCache(key, value) { | |
localStorage.setItem(key, value); | |
} | |
function getCache(key) { | |
return localStorage.getItem(key); | |
} | |
// Generate a unique id based on the input's properties | |
// Even after the page is refreshed, the id will be the same | |
function generateId(element) { | |
return element.id || element.name || element.placeholder; | |
} | |
// Save the value to cache | |
function onInput(event) { | |
const id = generateId(event.target); | |
// Update the value only when it's not empty. This is to avoid accidentally clear up the input box or leave a space but press enter key | |
if (event.target.value !== undefined && event.target.value !== null && event.target.value.trim() !== "") { | |
setCache(id, event.target.value); | |
} | |
} | |
// When pressing cmd + shift + p, retrieve the value from cache to the active input | |
function onKeyCombo(event) { | |
if (event.metaKey && event.shiftKey && event.key === "p") { | |
event.preventDefault(); | |
const id = generateId(event.target); | |
const value = getCache(id); | |
event.target.value = value; | |
} | |
} | |
let loaded = false; | |
if (!loaded) { | |
// Listen to all input events | |
for (var i = 0; i < textboxes.length; i++) { | |
textboxes[i].addEventListener("input", onInput); | |
textboxes[i].addEventListener("keydown", onKeyCombo); | |
} | |
loaded = true; | |
} | |
console.log("Type Guard Loaded"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment