Skip to content

Instantly share code, notes, and snippets.

@ampcpmgp
Last active October 30, 2024 01:33
Show Gist options
  • Save ampcpmgp/726719fb65637f31bc702923724fbac2 to your computer and use it in GitHub Desktop.
Save ampcpmgp/726719fb65637f31bc702923724fbac2 to your computer and use it in GitHub Desktop.
for bookmarklet
main();
async function main() {
clickXXXButton();
setPageXXXData();
}
// your functions
function clickXXXButton() {}
function setPageXXXData() {}
// helper functions
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function $(selector) {
return document.querySelector(selector);
}
function $$(selector) {
return Array.from(document.querySelectorAll(selector));
}
function $contain(selector, text) {
return $$(selector).find((item) => item.textContent.indexOf(text) > -1);
}
function $containExact(selector, text) {
return $$(selector).find((item) => item.textContent === text);
}
function readScript(src) {
return new Promise((resolve, reject) => {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// https://github.com/neos21/frontend-sandboxes/blob/master/web-audio-beep-morse-code/index.html
async function beep(options = { sec: 0.1, times: 1, interval: 0.1 }) {
let { times = 1 } = options;
const { sec = 0.1, interval = 0.1 } = options;
function play() {
return new Promise((resolve) => {
// Create Audio Context
const audioContext = new window.AudioContext();
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.connect(gain);
gain.connect(audioContext.destination);
// Set Options
oscillator.type = "sine";
oscillator.frequency.value = 440;
gain.gain.value = 0.3;
// Start
oscillator.onended = () => {
gain.disconnect(audioContext.destination);
oscillator.disconnect(gain);
resolve();
};
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + sec);
});
}
while (times-- > 0) {
await play();
await sleep(interval * 1000);
}
}
function downloadFile(filename, data, format = "plain") {
if (format === "json") {
data = JSON.stringify(data, null, 2);
} else if (format === "csv") {
data = data
// escape double quotes and add double quotes
.map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`))
.map((row) => row.join(","))
.join("\n");
}
const blob = new Blob([data], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = filename;
a.click();
document.body.removeChild(a);
}
function speak(message) {
const synth = window.speechSynthesis;
const utterThis = new SpeechSynthesisUtterance(message);
synth.speak(utterThis);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment