Skip to content

Instantly share code, notes, and snippets.

@FdelMazo
Last active May 21, 2023 18:15
Show Gist options
  • Save FdelMazo/e353960f1a51ebfef9dc5dc1aba9c0b7 to your computer and use it in GitHub Desktop.
Save FdelMazo/e353960f1a51ebfef9dc5dc1aba9c0b7 to your computer and use it in GitHub Desktop.
Browser extension demo
const DATA = [
{
q: "Q",
a: ["A1"],
}
]
const css = `
.a:hover {
font-style: italic !important;
}
`;
const style = document.createElement('style');
style.textContent = css;
document.head.append(style);
const std = (txt) => {
return txt
.replaceAll(' ', '')
.replaceAll(',', '')
.replaceAll('.', '')
.replaceAll('á', 'a')
.replaceAll('é', 'e')
.replaceAll('í', 'i')
.replaceAll('ó', 'o')
.replaceAll('ú', 'u')
.toLowerCase()
}
const match = (haystack, needle) => {
return std(haystack.textContent).includes(std(needle));
}
const addClass = (txt, className) => {
for (let element of elements) {
for (let child of element.childNodes) {
if (child.nodeType === 3 && match(child, txt)) {
element.classList.add(className);
}
}
}
}
const addTitle = (txt, title) => {
for (let element of elements) {
for (let child of element.childNodes) {
if (child.nodeType === 3 && match(child, txt)) {
element.setAttribute('title', title);
}
}
}
}
const elements = document.getElementsByTagName('*');
for (let question of DATA) {
for (let a of question.a) {
addClass(a, 'a');
}
}
for (let question of DATA) {
const idx = DATA.indexOf(question)
if (match(document.body, question.q)) {
addTitle(question.q, idx);
for (let a of question.a) {
addTitle(a, idx);
}
}
}
{
"manifest_version": 2,
"name": "Q&A",
"version": "1.0",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"main.js"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment