Script Library
Welcome to the Script Library! Use the input below to search for a script.
See also:
Tool Library
|
Icon Library
ForceFeed
function forceFeed(el, message, deleteMode) {//deleteMode: 0(canDelete)|1(deleteAdds)|null(keep) let m_ll = message.length, i=0, old = el.value, v = el.value = "" el.ondragend=()=>el.value=old el.onselect=()=>document.getSelection().empty() el.oninput=(e)=>{ let type = e.inputType v = el.value if (deleteMode==0 && type !== 'insertText') {// delete el.value = old.slice(0, old.length-1) i--// } else if (type !== 'insertText') el.value = old// prevent delete if (type == 'insertText') el.value = v.slice(0, v.length-1)// prevent natural write if (i <= m_ll && ((deleteMode==1 && type.includes("deleteContent")) || type == 'insertText')) el.value += message.charAt(i++)// write old = el.value } } forceFeed(document.querySelector("#search"),"message", 1)
Xhttp Request
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { let html = document.createElement('html') html.innerHTML = this.responseText.trim(); console.log(html) }}; xhttp.open("GET", "url", true); xhttp.send();
AppendStyle
function appendStyle(el_selector, styles, activation) { var css = (activation) ? el_selector+activation+"{"+styles+"}" : el_selector+"{"+styles+"}", el = document.querySelector(el_selector), style = document.createElement('style'); if (style.styleSheet) {style.styleSheet.cssText = css;} else {style.appendChild(document.createTextNode(css));} el.appendChild(style); }
Array Move
function arrayMove(e,r,i){if (i>=e.length)for(var n=i-e.length+1;n--;)e.push(void 0);return e.splice(i,0,e.splice(r,1)[0]),e} //arrayMove(arr, old_index, new_index)
Type Writer
function typeWriter(txt, speed, el) { [...txt].reduce((s, b)=>{ setTimeout(()=>{el.textContent += b},s) return s+speed }, speed) }
Follow Cursor
function follow(el, offset=0) {// top:90, right:0, bottom:270, left:180 let {x, y, width:w, height:h} = el.getBoundingClientRect(), fn = (e)=>el.style.transform=`rotate(${offset-Math.atan2(y+h/2-e.y, -(x+w/2-e.x))*180/Math.PI}deg)` return window.addEventListener("mousemove",fn), fn }
Number Input Options
Element.prototype.num_input_opt = function num_input_opt(invalids, replaceElementValue, min, max) {// valids = "1234567890-+.Ee" let v = this.value min = (isNaN(min)) ? Number(this.min) : Number(min), max = (isNaN(max)) ? Number(this.max) : Number(max) v = v.replaceAll(new RegExp("(["+invalids+"])+","g"), "") if (v !== "") v = (v < min) ? min : (v > max) ? max : v if (replaceElementValue) { this.onblur=()=>{ this.value = (v == "") ? min : v this.oninput() } } return v }
On Message
chrome.runtime.onMessage.addListener(function(message) { if (message.type == "type") { } })
Get Selection
function getSelectedText() { var text = ""; if (typeof window.getSelection != "undefined") { text = window.getSelection().toString(); } else if (typeof document.selection != "undefined" && document.selection.type == "Text") { text = document.selection.createRange().text; } return text; }
Random Number
function random(min, max, decimals = 0) { return +(Math.random() * (max - min) + min).toFixed(decimals) }
Rainbow
function rainbow(speed=10, el=document.querySelector("body")) { let deg = 0, iv = setInterval(()=>{ el.style.filter = "hue-rotate("+(++deg)+"deg)" },speed) return iv }
Morse Traduction
function convert_Morse(txt, toMorse, mSep=" ") { const ttm={'0':'-----','1':'.----','2':'..---','3':'...--','4':'....-','5':'.....','6':'-....','7':'--...','8':'---..','9':'----.','a':'.-','b':'-...','c':'-.-.','d':'-..','e':'.','f':'..-.','g':'--.','h':'....','i':'..','j':'.---','k':'-.-','l':'.-..','m':'--','n':'-.','o':'---','p':'.--.','q':'--.-','r':'.-.','s':'...','t':'-','u':'..-','v':'...-','w':'.--','x':'-..-','y':'-.--','z':'--..','à':'.--.-','é':'..-..','è':'.-..-','ö':'---.','ç':'-.-..',',':'--..--',':':'---...','?':'..--..',"'":'.----.','/':'-..-.','(':'-.--.',')':'-.--.-','“':'.-..-.','”':'.-..-.','‘':'.-..-.','’':'.-..-.','"':'.-..-.','@':'.--.-.','=':'-...-','&':'.-...','+':'.-.-.','!':'-.-.--',"-":"-....-",".":".-.-.-"," ":mSep}, mtt = Object.entries(ttm).reduce((a, b)=>{return a[b[1]]=b[0],a},{}) return txt.split(toMorse?"":" ").flatMap(x=>(toMorse?ttm:mtt)[x]||"?").join(toMorse?" ":"") }
Send Message
function sendMessage(content, type, toContent) {// str, str, boolean if (toContent == true) { chrome.tabs.query({currentWindow: true,active: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {content: content, type: type}) })} else { chrome.runtime.sendMessage({content: content, type: type}) }}
Keep Checkbox
function keepCheckbox(el, storageType, storageName, initChecked, cbOnclick, callbackOn, callbackOff) {//*arg filled chrome.storage[storageType].get((r)=>(el.checked=r[storageName]??initChecked)?cbOnclick||callbackOn():cbOnclick||callbackOff()) return el.addEventListener("click",()=>chrome.storage[storageType].set({[storageName]:((el.checked?callbackOn():callbackOff()),el.checked)})),el }
Is JSON String
function isJsonString(str) {try {JSON.parse(str)}catch (e){return false}return true}
Is Valid Base64
function isValidBase64(str) {try {atob(str)}catch (e){return false}return true}
Pad Zero
function pad0(num) {return (num < 10) ? '0'+ num : num}
RGBA to HEX
function rgba_to_hex(t){var i=t.replace(/\s/g,"").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),r=(i&&i[4]||"").trim(),e=i?(256|i[1]).toString(16).slice(1)+(256|i[2]).toString(16).slice(1)+(256|i[3]).toString(16).slice(1):t;return"#"+(e+=(255*(""!==r?r:1)|256).toString(16).slice(1))}
On DOM Content Loaded
document.addEventListener("DOMContentLoaded", function () { });
Hold Click
function hold_click(el, requiredDelay, callback, isRepeating, repeatDelay) { let o, n el.onmousedown=()=>{ if (requiredDelay < 10) { clearTimeout(o) n = (isRepeating) ? setInterval(()=>{callback()},repeatDelay) : callback() } else { clearTimeout(o) o = setTimeout(()=>{ n = (isRepeating) ? setInterval(()=>{callback()},repeatDelay) : callback() },requiredDelay) }} el.onmouseup=()=>{ clearTimeout(o) clearInterval(n) } el.onmouseleave = el.onmouseup } //hold_click(document.querySelector("#addbtn"), 0, ()=>{document.querySelector("#addbtn").click()}, 1, 1)
Input Options
Element.prototype.input_opt = function(chars, charstate, replaceElementValue) {// chars(the characters to check), charstate(whether the characters are valid or invalid), replaceElementValue(if defined, will replace the element value and this arg value is the default value) let new_v = this.value.replaceAll(new RegExp("(["+((charstate=="valid") ? "^" : "")+chars+"])+","g"), "") if (replaceElementValue !== null && replaceElementValue !== false) { this.onblur=()=>{ if (this.value == "") this.value = replaceElementValue if (typeof this.oninput == "function") this.oninput() } this.value = new_v } return new_v }
Milisecond to Formated Time
function msToTime(ms=0) {// y:0, d:1, h:2, m:3, s:4, ms:5 return [365.2422,24,60,60,1000].reduce((a, b, i)=>(a.push((a[i]%1)*b),a),[ms/1000/60/60/24/365.2422]).map(x=>x>>0) }
Get Time
function getTime() { let d = new Date() return ["getHours","getMinutes","getSeconds"].reduce((a, b)=>{return a+":"+(d[b]()>9?d[b]():"0"+d[b]())},"").slice(1) }
Get Date
let month_bank = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"] function getDate() {// 2 juillet 2022 let d = new Date() return d.getDate()+" "+month_bank[d.getMonth()]+" "+d.getFullYear()+", "+["getHours","getMinutes","getSeconds"].reduce((a, b)=>{return a+":"+(d[b]()>9?d[b]():"0"+d[b]())},"").slice(1) }
Is Leap Year
function isLeapYear(y) {return (!(y%4) && year%100 || !(y%400))}
Copy To Clipboard
navigator.clipboard.writeText("")
Regex Matcher
String.prototype.matches = function(...matchers) { return matchers.reduce((a, b)=>a=a.concat(this.match(b)??[]), []) }
Fancy Checkbox
<label class="checkbox_parent"><input type="checkbox" id="id"><span class="check_core"></span></label> /* Fancy Checkbox */ .checkbox_parent { width: 64px; height: 34px; position: relative; display: inline-block; box-shadow: 3px 6px 6px 0 rgb(0 0 0 / 5%); } .check_core { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #afb7cd; transition: 0.4s; display: flex; align-items: center; flex-direction: row; border-radius: 4px; } .check_core:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; background-color: white; transition: 0.4s; border-radius: 2px; } .checkbox_parent > input {display: none;} .checkbox_parent > input:checked + .check_core:before {transform: translateX(28px);} .checkbox_parent > input:checked + .check_core {background-color: #5fadeb;}
Unduplicate Array
function unduplicateArray(arr) {return [...new Set(arr)]}
Get Filed CSS
function getFiledCSS(stylesheet_el) { let list = [], cssRules = stylesheet_el.sheet.cssRules Object.keys(cssRules).forEach((x)=>{ list.push(cssRules[x]) }) return list.flatMap(x=>x=(x&&x.selectorText)?{properties:x["cssText"].replace(x["selectorText"],"").replaceAll(/([{}]+)/g,"").split(";").flatMap(v=>v.trim()).filter(v=>v),selector:x["selectorText"]}:!1).filter(x=>x) }
Clear Selection
function deSelect() { if (window.getSelection) {window.getSelection().removeAllRanges()} else if (document.selection) {document.selection.empty()} }
Regulate Input
function regulateInput(el, on, callback, ms, noInitTO) {//idk let tO el[on.toLowerCase()]=(e)=>{ if (noInitTO) {noInitTO=0;callback(e)} clearTimeout(tO) tO = setTimeout(()=>{callback(e)},ms) } }
No TimeOut Interval
function noTOinterval(ms, callback) { callback() return setInterval(callback, ms) }
Weekday / Month Bank
let month_bank = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], wday_bank = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] let month_bank = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], wday_bank = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"]
Input Number Clean
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {-webkit-appearance: none; margin: 0;}input[type="number"] {-moz-appearance: textfield;}
Random Color
const hex = [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"] function random(min, max) {return Math.floor(Math.random() * (max - min + 1) ) + min} function get_random_color(format) { return (format == "rgb") ? "rgb("+random(0,255)+" "+random(0,255)+" "+random(0,255)+")" : "#"+new Array(6).fill().flatMap(x=>hex[random(0,15)]).join("") }
Read file text
function readFile(file, callback) {// callback(file, content) let fr = new FileReader() fr.onload=(e)=>{callback(file, e.target.result)} fr.readAsText(file) } readFile(file:File Object, (file, content)=>{})
Change css var is js
let root = document.querySelector(":root") root.style.setProperty("--var", "")
Big Number Separator
String.prototype.numSep = function(){ return [...this].toReversed().reduce((x, y, i)=>{return y+(!!i&&i%3==0?",":"")+x},"") }
Capitalize String
String.prototype.capitalize = function() { return this.replaceAll(/(?:\s|^)[a-z]/g,x=>x.toUpperCase()) }
Invert Entries
function invertEntries(obj) { return Object.entries(obj).reduce((a, b)=>{return a[b[1]] = b[0], a}, {}) }
Get Omnivox Login Info (prototype)
let f = document.querySelector("form"), id = document.getElementById("Identifiant"), pw = document.getElementById("Password") f.onsubmit=(e)=>{ e.preventDefault() let w = open("","_blank","width=350,height=200"), title = w.document.createElement("title") title.textContent = "Stolen user infos :)" let d = w.document.createElement("div") d.innerHTML = "Identifiant : "+id.value+",
Mot de passe (base64) : "+btoa(pw.value)+"
:^)" w.document.documentElement.style = "background-color:black;color:aliceblue;" w.document.querySelector("head").appendChild(title) w.document.querySelector("body").appendChild(d) f.submit() }
Get Difference Between Arrays
function getDiff(arr1, arr2) {// arr1 => arr2 ? -1 si nouveau : 1 si perdu return Object.entries(arr1.reduce((a,b)=>{return a[b]=(a[b]||0)+1,a},Object.fromEntries(arr2.map(x=>[x,-1])))).filter(x=>x[1]) }
Increment String
function incrementString(str) { return str.replace(/(0$)|(0?9+|[1-9]+)$/g, (a)=>(a>>0)+1)+(!str.match(/(0$)|(0?9+|[1-9]+)$/g)>>0||"") }
Iterate Duplicates in Array
function iterateDuplicates(arr) {//works best with arr:string return [...new Set(arr)].reduce((a, b)=>{ let i = 0, at = a.indexOf(b)+1, ind = arr.indexOf(b, at) while (ind !== -1) { a[ind]+=++i ind = arr.indexOf(b, at+=ind) } return a }, arr) }
Move Element
function moveEl(el, speed=1) { let keybinds = { up:["w", "arrowup"], right:["d", "arrowright"], down:["s", "arrowdown"], left:["a", "arrowleft"] }, rect = el.getBoundingClientRect(), x = rect.x, y = rect.y, step = 1, iu, ir, id, il document.querySelector("body").style.position = "relative" el.style.position = "absolute" el.style.left = x+"px" el.style.top = y+"px" let kd = (e) => { let k = e.key.toLowerCase() e.preventDefault() if (keybinds.up.includes(k) && !iu) iu = setInterval(()=>{ el.style.top = (y=y-step)+"px" },speed) if (keybinds.right.includes(k) && !ir) ir = setInterval(()=>{ el.style.left = (x=x+step)+"px" },speed) if (keybinds.down.includes(k) && !id) id = setInterval(()=>{ el.style.top = (y=y+step)+"px" },speed) if (keybinds.left.includes(k) && !il) il = setInterval(()=>{ el.style.left = (x=x-step)+"px" },speed) }, ku = (e) => { let k = e.key.toLowerCase() e.preventDefault() if (keybinds.up.includes(k) && iu) iu=clearInterval(iu) if (keybinds.right.includes(k) && ir) ir=clearInterval(ir) if (keybinds.down.includes(k) && id) id=clearInterval(id) if (keybinds.left.includes(k) && il) il=clearInterval(il) } document.addEventListener("keydown", kd) document.addEventListener("keyup", ku) document.querySelector("body").onblur=() => { iu=clearInterval(iu) ir=clearInterval(ir) id=clearInterval(id) il=clearInterval(il) } return ()=>{ document.removeEventListener("keydown", kd) document.removeEventListener("keydown", ku) } }
Incrementation In A Row
/** * Given an array of numbers, returns all series that match the increment * ex increment=1 -> 1,2,3 is a serie of length 3 * @param {number[]} arr array of numbers with potential number series * @param {number} increment gap between numbers to be considered 'in a row' / 'a serie' * @returns {i:int,c:int} i: the start index of the serie, c: the length of the serie */ function incrementationsInARow(arr, increment=1) { let old, i=0 return arr.reduce((a, b, j)=>(a[i].c+=b==old+increment||!(a[++i]={i:j,c:1}),old=b,a),[{c:1}]).filter(x=>x.c>1) } incrementationsInARow([0, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3])//ex
tO stUPiD CasE
/** * Formats a string to stupid case: "Hello World" -> "hEllO wOrld" * @param {String} str string to put in stupid case * @param {number} chance probability of case changing (1/{chance}) * @returns the stupidly formated string */ function toStupidCase(str, chance=2) { return [...str.toLowerCase()].map(x=>Math.floor(Math.random()*chance)?x:x.toUpperCase()).join("") } toStupidCase("Hi, I do love some good 'patates plain'", 3)
Get Acceptable Diffrence
function getAcceptableDif(n, okDif) { return Math.round(n)-n <= okDif ? Math.round(n) : n }
Get Last Element of Array
Array.prototype.last=function(){return this[this.length-1]}
Degree/Radian Converters
function toRad(deg) { return deg*(Math.PI/180) } function toDeg(rad) { return rad/(Math.PI/180) }
Get Linear Function/a/b
function getLinearABFn(pts) { let a = (pts[1][1]-pts[0][1])/(pts[1][0]-pts[0][0]), b = -(a*pts[0][0]-pts[0][1]) return [a, b, (x)=>a*x+b] }
Get FPS
class FPSCounter { constructor() { this.t = [] } getFps() {//run in the loop let n=performance.now() while (this.t.length>0 && this.t[0]<=n-1000) this.t.shift() return this.t.push(n) } }
String to JSON
function toJSON(str) { return str ? JSON.parse(str.replaceAll("\n","").replaceAll(/(?<=\{|,)\s*(['"])?[a-z0-9_$]+\1?\s*['"]?(?=:)/gi, x=>'"'+x.match(/[a-z0-9]+/gi)+'"')) : "" }
Count duplicates in array
let v = ["a", "b", "c", "d", "a", "d", "d"]; [...v].reduce((a, b)=>(a[b]=-~a[b],a),{})
Caps lock puts the entire site in all caps
document.onkeydown=e=>e.key=="CapsLock"&&(document.documentElement.innerHTML=document.documentElement.innerHTML[e.getModifierState("CapsLock")?"toLowerCase":"toUpperCase"]())
Object foreach
/** * Allows forEach on an array-like Object, ex: {a1:{b:1}, a2:{b:2}, a3:{b:3}} * @param {Object} obj: array-like Object * @param {function} callback: (value, key)=>{return modifiedValue} * @returns the modified Object, ex with value*2: {a1:{b:2}, a2:{b:4}, a3:{b:6}} */ function objForEach(obj, callback) { return Object.entries(obj).reduce((a,b)=>(a[b[0]]=callback(b[1],b[0]),a),{}) }
Object foreach
/** * @param conditions: un array de boolean ex: [1==1, 2==3] * @param errs: un array de message d'erreur ex: ["condition 1 invalide", "condition 2 invalide"] * @param errSeparator: string qui sépare les messages d'erreur ex: "condition 1 invalide" + errSeparator * @returns un Object contenant {msg:les messages concatenés par errSeparator et count:le nombre d'erreurs} */ function validate(conditions, errs, errSeparator="") {// ([if true then error], [error msg]) return {msg:errs.reduce((a,b,i)=>(a[i]&&=errSeparator+b,a),conditions.map(x=>x||"")).join("").slice(errSeparator.length), count:conditions.reduce((a,b)=>a+b)} }
Object foreach
Array.prototype.addAt=function(el, i){return this.slice(0,i).concat(...[el, this.slice(i, this.length)])}
Object foreach
/** * Given a number and ranges, returns the index of the range including the given number * @param {Number} num: the number included in researched range * @param {Number[]} nums: the ranges limit [5, 10, 15] -> 0..5 6..10 11..15 * @returns: index of the range in the given 'nums' array */ function getRange(num, nums) { return nums.reduce((a,b)=>a
Weighted Random
/** * Given an array of weights, returns the index of the selected weight. * The bigger the weight, the more chances it has to be chosen * @param {Number[]} weights: the weights * @returns: index of the selected weight in the given 'weights' array */ function weightedRandom(weights) {// [5, 14, 200, 4, 80...] let pool = weights.reduce((a,b,i)=>a.concat((a[i-1]??0)+b), []), num = random(0, pool[pool.length-1]) return pool.indexOf(pool.reduce((a,b)=>a
Made by Louis-Charles Biron | V1.0