winzik/skeleton-chrome/content/content.js

87 lines
2.9 KiB
JavaScript

// The content script: runs inside the pages of manifest.json "content_scripts.matches" (an isolated world: it sees
// the page's DOM, not its JavaScript). It highlights the chosen word, shows a small badge with the count, and tells
// the background (the number on the toolbar button). Not an ES module: no import here (Chrome loads it as a script).
(() => {
const MARK = 'xh-mark';
const BADGE_ID = 'xh-badge';
let count = 0;
function clear() {
for (const mark of document.querySelectorAll(`mark.${MARK}`)) {
mark.replaceWith(document.createTextNode(mark.textContent));
}
document.body.normalize();
document.getElementById(BADGE_ID)?.remove();
}
function highlight(term, color) {
clear();
count = 0;
if (!term) return 0;
const needle = term.toLowerCase();
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
acceptNode: (node) => (node.parentElement?.closest('script, style, textarea, input, mark, [contenteditable]')
? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
});
const nodes = [];
while (walker.nextNode()) nodes.push(walker.currentNode);
for (const node of nodes) {
const text = node.nodeValue;
const lower = text.toLowerCase();
let at = lower.indexOf(needle);
if (at < 0) continue;
const fragment = document.createDocumentFragment();
let from = 0;
while (at >= 0) {
fragment.append(text.slice(from, at));
const mark = document.createElement('mark');
mark.className = MARK;
mark.style.backgroundColor = color;
mark.textContent = text.slice(at, at + needle.length);
fragment.append(mark);
count++;
from = at + needle.length;
at = lower.indexOf(needle, from);
}
fragment.append(text.slice(from));
node.replaceWith(fragment);
}
if (count > 0) {
const badge = document.createElement('div');
badge.id = BADGE_ID;
badge.textContent = chrome.i18n.getMessage('matchesOnPage', [String(count)]);
document.body.append(badge);
}
return count;
}
async function run(force = false) {
const settings = await chrome.runtime.sendMessage({ type: 'getSettings' });
if (!settings || (!settings.enabled && !force)) {
clear();
count = 0;
} else {
highlight(settings.term, settings.color);
}
chrome.runtime.sendMessage({ type: 'count', count }).catch(() => {});
return count;
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === 'highlight') {
run(true).then((n) => sendResponse({ count: n }));
return true;
}
if (message?.type === 'getCount') {
sendResponse({ count });
}
return false;
});
// the options changed (here, in the popup or on another computer): highlight again
chrome.storage.onChanged.addListener((_changes, area) => {
if (area === 'sync') run();
});
run();
})();