Skip to main content

Responsive Bootstrap Card.Img

CHS
0 likes • Jan 25, 2023 • 3 views
JavaScript
Loading...

More JavaScript Posts

localStorage Cookie Consent

0 likes • Oct 9, 2023 • 120 views
JavaScript
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
export default function CookieBanner() {
// Initialize with a default value (false if not previously set in localStorage)
const [cookieConsent, setCookieConsent] = useState(() =>
localStorage.getItem('cookieConsent') === 'true' ? true : false
);
useEffect(() => {
const newCookieConsent = cookieConsent ? 'granted' : 'denied';
window.gtag('consent', 'update', {
analytics_storage: newCookieConsent
});
localStorage.setItem('cookieConsent', String(cookieConsent));
}, [cookieConsent]);
return !cookieConsent && (
<div>
<div>
<p>
We use cookies to enhance the user experience.{' '}
<Link href='/privacy/'>View privacy policy</Link>
</p>
</div>
<div>
<button type="button" onClick={() => setCookieConsent(false)}>Decline</button>
<button type="button" onClick={() => setCookieConsent(true)}>Allow</button>
</div>
</div>
)
}

copyString.js

0 likes • Nov 8, 2023 • 5 views
JavaScript
function copyString(text){
async function navigatorClipboardCopy(text){
if(document.location.protocol != "https:"){
return false;
}
return new Promise((resolve, reject)=>{
navigator.clipboard.writeText(text).then(()=>{resolve(true);}, ()=>{resolve(false);});
});
}
function domCopy(text){
if(!(document.execCommand)){
console.warn("They finally deprecated document.execCommand!");
}
const input = document.createElement('textarea');
input.value = text;
document.body.appendChild(input);
input.select();
const success = document.execCommand('copy');
document.body.removeChild(input);
return success;
}
function promptCopy(){
prompt("Copy failed. Might have ... somewhere. Check console.", text);
console.log(text);
}
function done(){
alert("Copied to clipboard");
}
navigatorClipboardCopy(text).catch(()=>{return false;}).then((success)=>{
if(success){
done();
}else{
if(domCopy(text)){
done();
}else{
promptCopy();
}
}
});
}

URL Search Term Generator

CHS
0 likes • Jan 17, 2021 • 0 views
JavaScript
const getSearchTerm = delimiter => {
let searchTerm = "";
for (let i = 1; i < commands.length - 1; i++)
searchTerm = searchTerm + commands[i] + delimiter;
searchTerm += commands[commands.length - 1];
return searchTerm;
};

Scrape twitter

0 likes • Sep 2, 2023 • 9 views
JavaScript
//Allegedly never tested on the twitter website
function scrapeScreen(){
let articles = Array.from(document.getElementsByTagName("article"));
let results = [];
for(let tweet of articles){
const isAnAd = Array.from(tweet.querySelectorAll("span")).map((e)=>e.textContent).includes("Ad");
if(isAnAd){
//console.log(tweet, "is an ad. Skipping...");
continue;
}
const userName = tweet.querySelector("[data-testid='User-Name'] > div:nth-child(2) > div > div")?.textContent;
const tweetContent = tweet.querySelector("[data-testid='tweetText']")?.textContent;
const timeStamp = tweet.querySelector("time")?.getAttribute("datetime");
const tweetLink = tweet.querySelector("time")?.parentElement?.getAttribute("href");
if((!userName) || (!tweetContent)) continue;
results.push({
username: userName,
tweetText: tweetContent,
timeStamp: timeStamp,
tweetLink: tweetLink
});
}
return results;
}
let scraped = scrapeScreen();
setInterval(()=>{
scraped = scraped.concat(
scrapeScreen().filter((tweet)=>{
for(let scrapedTweet of scraped){
if(scrapedTweet.username == tweet.username && scrapedTweet.tweetText == tweet.tweetText) return false;
}
return true;
})
);
}, 500); //Scrape everything on the screen twice a second
window.scrollIntervalId = setInterval(function(){
window.scrollBy(0, 1000);
}, 500); //Scroll for me
//http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, '\t')
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
setTimeout(()=>{
clearTimeout(window.scrollIntervalId);
delete window.scrollIntervalId;
console.save(scraped, "TwitterScrape" + Date.now() + ".json");
}, 60 * 1000 * 20); //Twenty minutes

Authenticate Discord User

0 likes • Mar 28, 2023 • 1 view
JavaScript
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'YOUR_BOT_TOKEN';
// When the bot is ready, log a message to the console
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// When a user sends a message, check if they are authenticated
client.on('message', async (msg) => {
if (!msg.author.bot && !msg.author.authenticated) {
const filter = (m) => m.author.id === msg.author.id;
const collector = msg.channel.createMessageCollector(filter, { time: 15000 });
// Send an authentication message to the user
msg.author.send('Please authenticate yourself by clicking this link: ' + generateAuthURL(msg.author.id));
collector.on('collect', async (m) => {
// Check if the message contains the authentication code
if (m.content.startsWith('!auth ')) {
const code = m.content.slice(6);
const { access_token } = await getAccessToken(code);
// Set the user's authenticated status and access token
msg.author.authenticated = true;
msg.author.access_token = access_token;
collector.stop();
}
});
collector.on('end', () => {
if (!msg.author.authenticated) {
msg.author.send('Authentication timed out.');
}
});
}
});
// Generate an authentication URL for the user
function generateAuthURL(userId) {
const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
const scopes = 'identify';
const clientID = 'YOUR_CLIENT_ID';
return `https://discord.com/api/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=code&scope=${scopes}&state=${userId}`;
}
// Exchange the authorization code for an access token
async function getAccessToken(code) {
const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');
const clientID = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
const res = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=authorization_code&code=${code}&redirect_uri=${redirectURI}&client_id=${clientID}&client_secret=${clientSecret}`,
});
return await res.json();
}
client.login(token);

Reverse a string

0 likes • Nov 19, 2022 • 1 view
JavaScript
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'