From 408073a40b5a58d4953c9d7b56e44bda09d4977a Mon Sep 17 00:00:00 2001 From: Rik Date: Mon, 16 Nov 2026 17:22:32 +1100 Subject: [PATCH] Nuke this: click anything away, remembered per site and per service (2.1.0) "Nuke this" replaces "Kill nag wall" in the popup. It sweeps for anti-adblock walls as before, then drops a picker on the page: hover highlights, click hides, Esc cancels. Clicking inside a full-screen overlay takes the whole overlay. Scroll locks and blur are undone. The pick is saved for the site and applied as user-origin CSS on every visit. When the element is named after a third-party script host on the page (.pelcro-* with js.pelcro.com), the service is learned and its overlay is hidden on any other site that shows the token. Shared platforms are never learned. The picker is the only content script that can change settings: the worker takes a save only from the top frame of a tab the popup armed, one save per arm, and validates selectors and tokens in shared/nuke-rules.js. Co-Authored-By: Claude Opus 5.5 --- .github/copilot-instructions.md | 5 +- CHANGELOG.md | 23 +++ PRIVACY.md | 5 +- README.md | 3 +- docs/store-listing.md | 7 +- package-lock.json | 4 +- package.json | 2 +- scripts/build.mjs | 2 +- scripts/store-art.mjs | 2 +- src/background/cosmetic.js | 29 ++++ src/background/main.js | 27 +++- src/background/nuke.js | 113 ++++++++++++++ src/background/state.js | 3 + src/content/nuke.js | 266 ++++++++++++++++++++++++++++++++ src/options/options.css | 1 + src/options/options.html | 11 +- src/options/options.js | 16 +- src/popup/popup.css | 8 +- src/popup/popup.html | 5 +- src/popup/popup.js | 31 +++- src/shared/nuke-rules.js | 168 ++++++++++++++++++++ test/e2e/extension.spec.mjs | 12 +- test/e2e/nuke.spec.mjs | 151 ++++++++++++++++++ test/fixtures/nuke.html | 28 ++++ test/unit/nuke.test.mjs | 101 ++++++++++++ 25 files changed, 993 insertions(+), 30 deletions(-) create mode 100644 src/background/nuke.js create mode 100644 src/content/nuke.js create mode 100644 src/shared/nuke-rules.js create mode 100644 test/e2e/nuke.spec.mjs create mode 100644 test/fixtures/nuke.html create mode 100644 test/unit/nuke.test.mjs diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index f391203..b6de25f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -28,7 +28,10 @@ Read README.md first; this file is the short list of things that bite. - The service worker can die at any time. State lives in `chrome.storage`; `apply.js` must stay idempotent. All listeners are registered synchronously at top level. - Settings changes must come from extension pages (`sender.url` is ours). Content scripts - may only send `tokens` and `wall`, neither of which changes settings. + may only send `tokens` and `wall`, neither of which changes settings. The one exception is + the "Nuke this" picker (`nuke:save`, `nuke:undo`, handled in `background/nuke.js`): a save + is accepted only from the top frame of a tab the popup armed, uses the arm up, and every + selector and token is validated in `shared/nuke-rules.js` before it reaches CSS. Keep it that narrow. - Chrome writes `_metadata/` into a loaded unpacked folder; `package.mjs` skips `_` paths. - Anything that must happen before a tab-under's redirect (popup opener registration, the last committed URL) is done synchronously at the top of the listener, before any await. diff --git a/CHANGELOG.md b/CHANGELOG.md index 543db9b..615613a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ ## [Unreleased] +## [2.1.0] - 2026-11-16 + +### Added +- "Nuke this" in the popup: click it, then click anything on the page, and it is hidden, + with scrolling and any blur undone. It stays gone on that site. Clicking inside a + full-screen overlay takes the whole overlay, dimmer included. Esc cancels; the page never + receives the picking click. +- Nuked things that belong to a third-party service (the element's class or id is named + after a script host on the page, like `.pelcro-*` with `js.pelcro.com`) teach SilentBlock + the service, and its overlay is then hidden on every other site that shows it. Shared + platforms (Google, Cloudflare, CDNs and the like) are never learned. +- Undo straight after a nuke from the on-page toast, per site from the popup, and for any + site or service from the new "Nuked" section in Settings. + +### Changed +- "Nuke this" replaces "Kill nag wall": pressing it also sweeps the page for anti-adblock + walls as before. "Always on this site" is now "Auto-kill nag walls here". + +### Security +- The picker is the only content script that can change settings, and only narrowly: the + service worker accepts a save only from the top frame of a tab the popup just armed, one + save per arm, and validates every selector and token before it reaches any stylesheet. + ## [2.0.3] - 2026-10-07 ### Changed diff --git a/PRIVACY.md b/PRIVACY.md index 4d93775..b8092e1 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,6 +1,6 @@ # SilentBlock privacy policy -Last updated: 28 September 2026 +Last updated: 16 November 2026 **SilentBlock collects nothing.** It has no accounts, no analytics, no telemetry and no servers. Nothing you browse, block or configure ever leaves your browser. @@ -14,7 +14,8 @@ servers. Nothing you browse, block or configure ever leaves your browser. including Google Safe Browsing or any other lookup service. - **Reads the pages you visit** in order to hide ads, remove anti-adblock walls and colour its toolbar icon. What it reads stays in the browser and is not stored. -- **Stores your settings** (paused sites, categories, display options) with your browser's +- **Stores your settings** (paused sites, categories, display options, and the things you + removed with "Nuke this", with the site or service they belong to) with your browser's extension storage. They stay in that browser. Export them from Settings if you want a copy. - **Keeps per-tab counts** (how many requests were blocked) in memory for the popup. They are cleared when you close the tab or the browser. diff --git a/README.md b/README.md index 50a4c57..19c1464 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ the extension and never downloads rules at runtime. | **Anti-adblock** | ~8,200 site-specific scriptlets (uBO semantics: `set-constant`, `abort-on-property-read`, `prevent-setTimeout`, `json-prune` and 30 others), run in the page before its own scripts, only on the sites listed. | | **Pop-ups and tab-unders** | New tabs a page opens are followed for their first few hops and closed if they land on one of ~3,000 `$popup` hosts. A tab sent to an ad right after the page reopened itself in a new tab is put back. | | **Malware and scams** | uBO Badware, URLhaus, the Phishing URL Blocklist and DurableNapkin's scam list: ~46,000 hosts blocked outright, plus ~36,000 individual phishing and malware page URLs checked on every navigation. A listed page gets a warning with "Back to safety" and "Continue anyway". This layer stays on for paused sites. No API keys and no lookups: every check is local. | -| **Nag walls** | "Kill nag wall" in the popup removes an anti-adblock overlay on demand, or on every visit with "Always on this site". | +| **Nuke this** | Click "Nuke this" in the popup, then click anything on the page: it is hidden, scrolling and blur are undone, and it stays gone on that site. Click inside a full-screen overlay and the whole overlay goes. If the thing was drawn by a third-party service (its class or id is named after a script host on the page, like `.pelcro-*` with `js.pelcro.com`), the service is remembered and its overlay is hidden on every other site that shows it. Big shared platforms (Google, Cloudflare, CDNs) are never learned. Undo from the page, the popup or Settings. | +| **Nag walls** | "Nuke this" also sweeps the page for anti-adblock overlays; "Auto-kill nag walls here" does that on every visit. | Every piece of CSS is injected as a *user* stylesheet: pages cannot see it, override it or block it with CSP. On ordinary sites SilentBlock patches no page APIs at all. diff --git a/docs/store-listing.md b/docs/store-listing.md index 11a88cf..89a7cf1 100644 --- a/docs/store-listing.md +++ b/docs/store-listing.md @@ -33,6 +33,9 @@ WHAT IT BLOCKS • Malware, phishing and scam sites, using URLhaus, the Phishing URL Blocklist, uBlock Origin's Badware list and a scam blocklist • "Turn off your ad blocker" walls, with one click, or automatically on sites you choose +NUKE THIS +Something still in your way? Click "Nuke this", click the thing, and it's gone, on that site from now on. If it came from a service lots of sites use, SilentBlock remembers the service and nukes it on those sites too. Changed your mind? Undo is one click. + THE ICON TELLS YOU WHAT HAPPENED • Blue: nothing on this page needed blocking • Green: ads and trackers blocked @@ -62,8 +65,8 @@ Leave each store's category as the existing listing has it (Firefox: Privacy & S **Permission justifications:** - `declarativeNetRequest`: applies the bundled filter lists with the browser's built-in request blocker. -- `scripting`: injects the bundled hiding rules and anti-adblock fixes into pages, and removes anti-adblock walls when the user asks. -- `storage`: saves the user's settings (paused sites, categories, display options). +- `scripting`: injects the bundled hiding rules and anti-adblock fixes into pages, and removes anti-adblock walls and hides page elements the user picks with "Nuke this". +- `storage`: saves the user's settings (paused sites, categories, display options, elements the user chose to hide). - `webNavigation`: knows when a page loads, to apply site-specific rules, follow new tabs opened by pages (pop-up blocking), and show the malware warning page. - `webRequest`: read-only, counts blocked requests per tab for the toolbar icon colour and the popup count. - Host permission ``: ads, trackers and malicious content can appear on any site; blocking and hiding must work on every site the user visits. diff --git a/package-lock.json b/package-lock.json index 2e5e136..44593c5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "silentblock", - "version": "2.0.3", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "silentblock", - "version": "2.0.3", + "version": "2.1.0", "devDependencies": { "@playwright/test": "^1.63.0", "selenium-webdriver": "^4.49.0" diff --git a/package.json b/package.json index 2621f45..6b46ed1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "silentblock", - "version": "2.0.3", + "version": "2.1.0", "private": true, "description": "Free, silent ad blocker for Chrome (MV3). No ads, no nags.", "type": "module", diff --git a/scripts/build.mjs b/scripts/build.mjs index 918aa84..bcbebb8 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -225,7 +225,7 @@ for (const cat of categories) { } out['content/unwall.js'] = `// Built from src/shared/unwall-core.js. Injected on demand by the popup and on -// per-site "always kill nag walls" hosts. Wrapped so a second injection is harmless. +// per-site "auto-kill nag walls" hosts. Wrapped so a second injection is harmless. (() => { ${unwallCore} unwallWatch(15000, () => chrome.runtime.sendMessage({ type: 'wall' }).catch(() => {})); diff --git a/scripts/store-art.mjs b/scripts/store-art.mjs index 100ee10..0bead01 100644 --- a/scripts/store-art.mjs +++ b/scripts/store-art.mjs @@ -41,7 +41,7 @@ async function render(dist, iconDir, out) { window.chrome = { runtime: { sendMessage: async (m) => m.type === 'popup:get' ? ${JSON.stringify(popupData)} - : m.type === 'settings:get' ? { state: { enabled: true, allowlist: ['intranet.example.com'], categories: { ads: true, privacy: true, annoyances: true, security: true }, unwallSites: ['recipes.example.com'], badge: false, statusIcon: true }, meta: ${JSON.stringify(meta)} } + : m.type === 'settings:get' ? { state: { enabled: true, allowlist: ['intranet.example.com'], categories: { ads: true, privacy: true, annoyances: true, security: true }, unwallSites: ['recipes.example.com'], nuked: { sites: {}, services: {} }, badge: false, statusIcon: true }, meta: ${JSON.stringify(meta)} } : {}, openOptionsPage() {}, }, diff --git a/src/background/cosmetic.js b/src/background/cosmetic.js index 28fbe7e..bf3e119 100644 --- a/src/background/cosmetic.js +++ b/src/background/cosmetic.js @@ -6,6 +6,7 @@ import { hostnameAndParents, shardOf } from '../shared/hostnames.js'; import { loadJSON, getMeta } from './data.js'; import { activeCategories } from './apply.js'; import { isPaused } from './state.js'; +import { nukeCss, siteSelectors, serviceTokenIndex, UNLOCK_CSS } from '../shared/nuke-rules.js'; const FLAG = { ghide: 1, ehide: 2, shide: 4, complexException: 8 }; @@ -76,6 +77,13 @@ export function rememberTop(tabId, hostname) { export function forgetTab(tabId) { topHosts.delete(tabId); + nukedServices.delete(tabId); +} + +// Learned services that fired on each tab's current page, for the popup. +const nukedServices = new Map(); +export function servicesNukedIn(tabId) { + return [...(nukedServices.get(tabId) || [])]; } async function topHostOf(tabId, fallbackUrl) { @@ -96,6 +104,12 @@ export async function onCommitted({ tabId, frameId, documentId, url }, state) { const top = frameId === 0 ? hostname : await topHostOf(tabId, url); if (isPaused(top, state)) return; + // "Nuke this" rules are the user's own, so list flags like $elemhide don't switch them off. + if (frameId === 0) { + nukedServices.delete(tabId); + await insert(tabId, frameId, documentId, nukeCss(siteSelectors(state.nuked, hostnameAndParents(hostname)))); + } + const flags = await hostFlags(hostname); if (flags & FLAG.ehide) return; const meta = await getMeta(); @@ -131,6 +145,7 @@ export async function onTokens(message, sender, state) { const hostname = new URL(sender.url).hostname; const top = await topHostOf(sender.tab.id, sender.tab.url || sender.url); if (isPaused(top, state)) return; + await nukeServices(message.tokens, sender, state); const flags = await hostFlags(hostname); if (flags & (FLAG.ghide | FLAG.ehide)) return; @@ -146,3 +161,17 @@ export async function onTokens(message, sender, state) { } if (hits.length) await insert(sender.tab.id, sender.frameId, sender.documentId, hideRule(hits)); } + +// A page showing a learned service's token gets that token hidden and the page unlocked. +// Tokens are lookup keys; only the copies stored in settings (validated) reach the CSS. +async function nukeServices(reported, sender, state) { + const idx = serviceTokenIndex(state.nuked); + if (!idx.size) return; + const seen = new Set(reported.slice(0, 5000)); + const hits = [...idx.keys()].filter((t) => seen.has(t)); + if (!hits.length) return; + const set = nukedServices.get(sender.tab.id) || new Set(); + for (const t of hits) for (const d of idx.get(t)) set.add(state.nuked.services[d].name); + nukedServices.set(sender.tab.id, set); + await insert(sender.tab.id, sender.frameId, sender.documentId, hideRule(hits) + UNLOCK_CSS); +} diff --git a/src/background/main.js b/src/background/main.js index 125fb6f..4dc9990 100644 --- a/src/background/main.js +++ b/src/background/main.js @@ -4,12 +4,13 @@ // for them. State lives in chrome.storage; nothing here relies on the worker staying alive. import { loadState, saveState, migrate, allowlistEntryFor, normalise } from './state.js'; import { applyAll, applyAction, desiredContentScripts } from './apply.js'; -import { onCommitted, onTokens, rememberTop, forgetTab } from './cosmetic.js'; +import { onCommitted, onTokens, rememberTop, forgetTab, servicesNukedIn } from './cosmetic.js'; import { onCreatedNavigationTarget, onTopNavigation, onNavigationError, forgetPopupTab, noteCommitted, lastUrlOf } from './popups.js'; import { resetTab, record, getStatus, levelOf, iconStateFor, forgetStatus } from './status.js'; import { checkNavigation, dangerHost, securityOn, bypass } from './security.js'; import { getMeta } from './data.js'; import { hostnameAndParents, normaliseHostname } from '../shared/hostnames.js'; +import { armNuke, onNukeMessage, clearSiteNukes, nukedCount } from './nuke.js'; const EXTENSION_ORIGIN = chrome.runtime.getURL(''); @@ -101,10 +102,15 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { const fromExtensionPage = typeof sender.url === 'string' && sender.url.startsWith(EXTENSION_ORIGIN); // Content scripts may say two things: "these classes/ids are on my page", and - // "I removed a nag wall". Neither changes settings. + // "I removed a nag wall". Neither changes settings. The one exception is the "Nuke this" + // picker, and nuke.js only listens to it in a tab where the popup armed it. if (!fromExtensionPage && sender.tab) { if (message.type === 'tokens') loadState().then((s) => onTokens(message, sender, s)).catch(() => {}); if (message.type === 'wall') loadState().then((s) => record(sender.tab.id, 'wall', null, s)).catch(() => {}); + if (message.type === 'nuke:save' || message.type === 'nuke:undo') { + onNukeMessage(message, sender).then(sendResponse, (err) => sendResponse({ error: String(err?.message || err) })); + return true; + } return false; } @@ -132,6 +138,8 @@ async function handle(msg) { const status = await getStatus(msg.tabId); out.pausedBy = allowlistEntryFor(info.hostname, state); out.unwall = hostnameAndParents(info.hostname).some((h) => state.unwallSites.includes(h)); + out.nuked = nukedCount(state, info.hostname); + out.nukedServices = servicesNukedIn(msg.tabId); out.status = { ...status, level: levelOf(status), icon: iconStateFor({ ...status, host: info.hostname }, state) }; } return out; @@ -158,6 +166,21 @@ async function handle(msg) { return { ok: true, pausedBy: allowlistEntryFor(hostname, state) }; } + case 'nuke:start': { + // Folded-in nag-wall sweep first (harmless where there is no wall), then the picker. + await armNuke(msg.tabId); + await chrome.scripting.executeScript({ target: { tabId: msg.tabId, allFrames: true }, files: ['content/unwall.js'] }).catch(() => {}); + await chrome.scripting.executeScript({ target: { tabId: msg.tabId, frameIds: [0] }, files: ['content/nuke.js'] }); + return { ok: true }; + } + + case 'nuke:clearSite': { + const hostname = normaliseHostname(msg.hostname); + if (!hostname) throw new Error('Not a valid hostname'); + await clearSiteNukes(hostname); + return { ok: true }; + } + case 'unwallNow': { // Every frame: walls also turn up inside embedded players and sandboxed page frames. await chrome.scripting.executeScript({ target: { tabId: msg.tabId, allFrames: true }, files: ['content/unwall.js'] }); diff --git a/src/background/nuke.js b/src/background/nuke.js new file mode 100644 index 0000000..e224dc2 --- /dev/null +++ b/src/background/nuke.js @@ -0,0 +1,113 @@ +// "Nuke this": the popup arms a tab, the picker (content/nuke.js) reports one click, and +// this file turns it into a saved rule. +// +// Content scripts normally cannot change settings. The picker is the one exception, and it +// is narrow: a save is accepted only from the top frame of a tab the popup armed in the last +// few minutes, and it uses the arm up. Undo is accepted only for the rule that save made, +// for a minute. Everything the picker sends is validated by nuke-rules.js. +import { loadState, saveState } from './state.js'; +import { record } from './status.js'; +import { hostnameAndParents, normaliseHostname } from '../shared/hostnames.js'; +import { cleanSelector, pickService, nukeCss, siteSelectors } from '../shared/nuke-rules.js'; + +const ARM_MS = 10 * 60 * 1000; +const UNDO_MS = 60 * 1000; +const armKey = (tabId) => `nukeArm:${tabId}`; +const lastKey = (tabId) => `nukeLast:${tabId}`; + +// storage.session survives the worker stopping between the click and the save. +async function take(key) { + const got = (await chrome.storage.session.get(key))[key]; + await chrome.storage.session.remove(key); + return got && got.until > Date.now() ? got : null; +} + +export async function armNuke(tabId) { + if (!Number.isInteger(tabId)) throw new Error('No tab'); + await chrome.storage.session.set({ [armKey(tabId)]: { until: Date.now() + ARM_MS } }); +} + +async function cssTarget(sender) { + return sender.documentId ? { tabId: sender.tab.id, documentIds: [sender.documentId] } : { tabId: sender.tab.id, frameIds: [0] }; +} + +async function css(method, sender, text) { + try { + await chrome.scripting[method]({ target: await cssTarget(sender), css: text, origin: 'USER' }); + } catch { + try { await chrome.scripting[method]({ target: { tabId: sender.tab.id, frameIds: [0] }, css: text, origin: 'USER' }); } catch { /* gone */ } + } +} + +function senderHost(sender) { + if (sender.frameId !== 0 || !sender.url || !/^https?:/.test(sender.url)) return null; + try { return normaliseHostname(new URL(sender.url).hostname); } catch { return null; } +} + +export async function onNukeMessage(msg, sender) { + const tabId = sender.tab.id; + const host = senderHost(sender); + if (!host) throw new Error('Not here'); + + if (msg.type === 'nuke:save') { + const selector = cleanSelector(msg.selector); + if (!selector) throw new Error('Bad selector'); + if (!(await take(armKey(tabId)))) throw new Error('Not armed'); + const service = pickService(host, msg.hosts, msg.tokens); + + const cur = await loadState(); + const nuked = structuredClone(cur.nuked); + nuked.sites[host] = [...new Set([...(nuked.sites[host] || []), selector])]; + let learned = false; + if (service) { + const prev = nuked.services[service.domain]; + learned = !prev || !prev.tokens.includes(service.token); + nuked.services[service.domain] = { + name: prev?.name || service.name, + tokens: [...new Set([...(prev?.tokens || []), service.token])], + from: prev?.from || host, + at: prev?.at || new Date().toISOString(), + }; + } + const state = await saveState({ nuked }); + if (!state.nuked.sites[host]?.includes(selector)) throw new Error('Rule not saved'); + + await chrome.storage.session.set({ + [lastKey(tabId)]: { until: Date.now() + UNDO_MS, host, selector, service: learned ? service : null }, + }); + await css('insertCSS', sender, nukeCss([selector])); + await record(tabId, 'wall', null, state).catch(() => {}); + return { ok: true, host, service: service ? { domain: service.domain, name: service.name } : null }; + } + + if (msg.type === 'nuke:undo') { + const last = await take(lastKey(tabId)); + if (!last || last.host !== host || last.selector !== msg.selector) throw new Error('Nothing to undo'); + const cur = await loadState(); + const nuked = structuredClone(cur.nuked); + const left = (nuked.sites[host] || []).filter((s) => s !== last.selector); + if (left.length) nuked.sites[host] = left; else delete nuked.sites[host]; + // Forget the service only if this nuke is what taught it that token. + if (last.service && nuked.services[last.service.domain]) { + const svc = nuked.services[last.service.domain]; + svc.tokens = svc.tokens.filter((t) => t !== last.service.token); + if (!svc.tokens.length) delete nuked.services[last.service.domain]; + } + await saveState({ nuked }); + await css('removeCSS', sender, nukeCss([last.selector])); + return { ok: true }; + } + + throw new Error('Unknown nuke message'); +} + +export async function clearSiteNukes(hostname) { + const cur = await loadState(); + const nuked = structuredClone(cur.nuked); + for (const h of hostnameAndParents(hostname)) delete nuked.sites[h]; + await saveState({ nuked }); +} + +export function nukedCount(state, hostname) { + return siteSelectors(state.nuked, hostnameAndParents(hostname)).length; +} diff --git a/src/background/state.js b/src/background/state.js index 7e8a5bf..973687a 100644 --- a/src/background/state.js +++ b/src/background/state.js @@ -4,6 +4,7 @@ // unconditionally). Here install writes defaults only when nothing is stored, and update // migrates in place. import { normaliseHostname } from '../shared/hostnames.js'; +import { normaliseNuked, emptyNuked } from '../shared/nuke-rules.js'; export const SCHEMA = 2; @@ -16,6 +17,7 @@ export function defaults() { allowlist: [], categories: { ads: true, privacy: true, annoyances: true, security: true }, unwallSites: [], + nuked: emptyNuked(), badge: false, statusIcon: true, }; @@ -44,6 +46,7 @@ export function normalise(raw) { allowlist: hostList(r.allowlist), categories, unwallSites: hostList(r.unwallSites), + nuked: normaliseNuked(r.nuked), badge: typeof r.badge === 'boolean' ? r.badge : d.badge, statusIcon: typeof r.statusIcon === 'boolean' ? r.statusIcon : d.statusIcon, }; diff --git a/src/content/nuke.js b/src/content/nuke.js new file mode 100644 index 0000000..b181445 --- /dev/null +++ b/src/content/nuke.js @@ -0,0 +1,266 @@ +// "Nuke this" picker. Injected into the top frame by the popup (via the service worker). +// Hover highlights, click nukes, Esc cancels. Clicking inside a full-screen overlay nukes the +// whole overlay, so one click takes the dimmer with the box. +// +// The page never sees this UI (closed shadow root) and never gets the click. What gets +// remembered is decided by the worker: this script only reports a selector, the class/id +// tokens around the element, and the third-party script hosts on the page. +(() => { + 'use strict'; + const G = globalThis; + if (G.__silentblockNuke) { G.__silentblockNuke.start(); return; } + + const html = document.documentElement; + const area = (el) => { + const r = el.getBoundingClientRect(); + return (r.width * r.height) / Math.max(1, innerWidth * innerHeight); + }; + + // ---- UI ------------------------------------------------------------------------------- + let ui = null; + function mount() { + if (ui) return ui; + const host = document.createElement('silentblock-nuke'); + host.style.cssText = 'all:initial!important;position:fixed!important;inset:0!important;z-index:2147483647!important;pointer-events:none!important;display:block!important'; + const root = host.attachShadow({ mode: 'closed' }); + root.innerHTML = ` +
\u{1F4A5} Click what you want gone. Esc cancels.
+
+

`; + html.appendChild(host); + ui = { host, bar: root.querySelector('.bar'), box: root.querySelector('.box'), toast: root.querySelector('.toast') }; + return ui; + } + + function unmount() { + ui?.host.remove(); + ui = null; + } + + // ---- picking -------------------------------------------------------------------------- + let picking = false; + let current = null; + + function targetAt(x, y) { + const el = document.elementFromPoint(x, y); + if (!el || el === html || el === document.body || el.localName === 'silentblock-nuke') return null; + // Outermost fixed/sticky ancestor that covers half the screen: that's the overlay. + let best = el; + for (let a = el; a && a !== document.body && a !== html; a = a.parentElement) { + const cs = getComputedStyle(a); + if ((cs.position === 'fixed' || cs.position === 'sticky') && area(a) >= 0.5) best = a; + } + return best; + } + + function highlight(el) { + current = el; + const { box } = mount(); + if (!el) { box.style.display = 'none'; return; } + const r = el.getBoundingClientRect(); + Object.assign(box.style, { display: 'block', left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` }); + } + + const swallow = (e) => { + if (!picking || !e.isTrusted) return; + e.preventDefault(); + e.stopImmediatePropagation(); + }; + const onMove = (e) => { if (picking) highlight(targetAt(e.clientX, e.clientY)); }; + const onScroll = () => { if (picking && current) highlight(current); }; + const onClick = (e) => { + if (!picking || !e.isTrusted) return; + swallow(e); + if (e.button !== 0) return; + const t = targetAt(e.clientX, e.clientY) || current; + if (t) nuke(t); + }; + const onKey = (e) => { + if (!picking || e.key !== 'Escape') return; + swallow(e); + stop(); + unmount(); + }; + + const BLOCKED = ['mousedown', 'mouseup', 'pointerdown', 'pointerup', 'auxclick', 'dblclick', 'contextmenu']; + function listen(on) { + const f = (on ? addEventListener : removeEventListener).bind(G); + f('mousemove', onMove, true); + f('click', onClick, true); + f('keydown', onKey, true); + f('scroll', onScroll, true); + for (const t of BLOCKED) f(t, swallow, true); + } + + function start() { + if (picking) return; + picking = true; + const u = mount(); + u.bar.style.display = ''; + u.toast.style.display = 'none'; + listen(true); + } + + function stop() { + picking = false; + listen(false); + if (ui) { ui.bar.style.display = 'none'; ui.box.style.display = 'none'; } + } + + // ---- what to remember ----------------------------------------------------------------- + // Generated class names (css-1x2y3z, sc-AbC12) change every deploy, so skip them. + function stable(name) { + if (!name || name.length < 2 || name.length > 40) return false; + if (/\d{3,}/.test(name) || /^(?:css|sc|jsx|emotion|styled|svelte|astro)[-_]/i.test(name)) return false; + return ((name.match(/[a-z][0-9]|[0-9][a-z]/gi) || []).length) < 3; + } + + function part(el) { + const tag = CSS.escape(el.localName); + if (el.id && stable(el.id)) return `#${CSS.escape(el.id)}`; + const cls = [...el.classList].filter(stable).slice(0, 3); + return cls.length ? `${tag}.${cls.map((c) => CSS.escape(c)).join('.')}` : tag; + } + + function unique(sel, el) { + try { + const m = document.querySelectorAll(sel); + return m.length === 1 && m[0] === el; + } catch { return false; } + } + + function selectorFor(t) { + let chain = part(t); + if (unique(chain, t)) return chain; + let cur = t; + for (let i = 0; i < 5; i++) { + const p = cur.parentElement; + if (!p || p === html) break; + chain = `${p === document.body ? 'body' : part(p)} > ${chain}`; + if (unique(chain, t)) return chain; + if (p === document.body) break; + cur = p; + } + // Last resort: a positional path from . + const steps = []; + for (let e = t; e && e !== document.body && e !== html; e = e.parentElement) { + let n = 1; + for (let s = e.previousElementSibling; s; s = s.previousElementSibling) if (s.localName === e.localName) n++; + steps.unshift(`${CSS.escape(e.localName)}:nth-of-type(${n})`); + } + const path = `body > ${steps.join(' > ')}`; + return steps.length && unique(path, t) ? path : null; + } + + // The element's own class/id tokens first, then wrappers no bigger than it, then children. + function tokensFor(t) { + const out = []; + const add = (e) => { + if (e.id) out.push(`#${e.id}`); + for (const c of e.classList) out.push(`.${c}`); + }; + add(t); + const a0 = area(t); + let depth = 0; + for (let a = t.parentElement; a && a !== document.body && a !== html && depth < 6; a = a.parentElement, depth++) { + if (area(a) <= a0 * 1.2 + 0.001) add(a); + } + for (const c of t.children) { + add(c); + for (const g of c.children) add(g); + } + return [...new Set(out)].slice(0, 60); + } + + function thirdPartyHosts() { + const hosts = new Set(); + const addUrl = (u) => { + try { + const url = new URL(u, location.href); + if (/^https?:$/.test(url.protocol) && url.hostname !== location.hostname) hosts.add(url.hostname); + } catch { /* not a URL */ } + }; + for (const s of document.scripts) if (s.src) addUrl(s.src); + for (const f of document.querySelectorAll('iframe[src]')) addUrl(f.src); + try { + for (const r of performance.getEntriesByType('resource')) { + if (r.initiatorType === 'script' || r.initiatorType === 'iframe') addUrl(r.name); + } + } catch { /* no timing API */ } + return [...hosts].slice(0, 200); + } + + // ---- nuking --------------------------------------------------------------------------- + function unlock() { + for (const el of [html, document.body]) { + if (!el) continue; + const cs = getComputedStyle(el); + if (cs.overflow === 'hidden' || cs.overflowY === 'hidden') { + el.style.setProperty('overflow', 'auto', 'important'); + el.style.setProperty('overflow-y', 'auto', 'important'); + } + if (cs.pointerEvents === 'none') el.style.setProperty('pointer-events', 'auto', 'important'); + } + for (const el of document.querySelectorAll('body > *, main, article, [role="main"], [style*="blur("]')) { + const cs = getComputedStyle(el); + if (cs.filter.includes('blur')) el.style.setProperty('filter', 'none', 'important'); + if (cs.backdropFilter && cs.backdropFilter.includes('blur')) el.style.setProperty('backdrop-filter', 'none', 'important'); + if (cs.filter.includes('blur') && cs.pointerEvents === 'none') el.style.setProperty('pointer-events', 'auto', 'important'); + } + } + + let toastTimer = 0; + function toast(text, undo) { + const { toast: box } = mount(); + const btn = box.querySelector('button'); + box.querySelector('p').textContent = text; + btn.hidden = !undo; + btn.onclick = undo ? () => { btn.hidden = true; undo(); } : null; + box.style.display = 'flex'; + clearTimeout(toastTimer); + toastTimer = setTimeout(unmount, 8000); + } + + async function nuke(t) { + stop(); + const selector = selectorFor(t); + const tokens = tokensFor(t); + const hosts = thirdPartyHosts(); + const prev = t.style.getPropertyValue('display'); + const prevPriority = t.style.getPropertyPriority('display'); + t.style.setProperty('display', 'none', 'important'); + unlock(); + if (!selector) { toast('Nuked for now. Couldn’t pin it down well enough to remember it.'); return; } + + let res; + try { + res = await chrome.runtime.sendMessage({ type: 'nuke:save', selector, tokens, hosts }); + } catch { res = null; } + if (!res || res.error) { toast('Nuked for now, but SilentBlock couldn’t remember it.'); return; } + + const where = res.service ? `, and on other ${res.service.name} sites` : ''; + toast(`Nuked. Gone on this site from now on${where}.`, async () => { + try { + const r = await chrome.runtime.sendMessage({ type: 'nuke:undo', selector }); + if (r && r.error) throw new Error(r.error); + if (prev) t.style.setProperty('display', prev, prevPriority); else t.style.removeProperty('display'); + toast('Un-nuked. It’s back.'); + } catch { + toast('Too late to undo here. Remove it in SilentBlock settings.'); + } + }); + } + + G.__silentblockNuke = { start }; + start(); +})(); diff --git a/src/options/options.css b/src/options/options.css index 65f55a5..ca77c0b 100644 --- a/src/options/options.css +++ b/src/options/options.css @@ -5,6 +5,7 @@ body { padding: 24px 16px 48px; font-size: 14px; } .top .shield { flex: none; display: block; } h1 { margin: 0; font-size: 22px; } h2 { margin: 0 0 2px; font-size: 15px; } +h3 { margin: 16px 0 0; font-size: 13px; color: var(--muted); } .top .hint { margin: 2px 0 0; } .card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px; box-shadow: var(--shadow); } diff --git a/src/options/options.html b/src/options/options.html index fff4012..35202af 100644 --- a/src/options/options.html +++ b/src/options/options.html @@ -40,9 +40,18 @@

Paused sites

    +
    +

    Nuked

    +

    Things you got rid of with "Nuke this" in the popup. They stay gone on that site. When the thing you nuked belonged to a service other sites use too (a paywall or pop-up company, say), SilentBlock remembers the service and nukes it on those sites as well. If you subscribe to a site that uses one of these services, remove it here so you can log in.

    +

    Sites

    +
      +

      Services

      +
        +
        +

        Nag-wall sites

        -

        On these sites SilentBlock watches for "turn off your ad blocker" walls and removes them as the page loads. Add one from the popup with "Always on this site".

        +

        On these sites SilentBlock watches for "turn off your ad blocker" walls and removes them as the page loads. Add one from the popup with "Auto-kill nag walls here".

          diff --git a/src/options/options.js b/src/options/options.js index baa5ffa..4da0592 100644 --- a/src/options/options.js +++ b/src/options/options.js @@ -42,17 +42,28 @@ function renderCategories() { } } -function renderList(listId, hosts, onRemove) { +function renderList(listId, hosts, onRemove, labelOf = (h) => h) { const ul = $(listId); ul.replaceChildren(); for (const h of hosts) { const btn = el('button', { type: 'button', textContent: 'Remove' }); btn.setAttribute('aria-label', `Remove ${h}`); btn.addEventListener('click', () => onRemove(h)); - ul.append(el('li', {}, el('span', { textContent: h }), btn)); + ul.append(el('li', {}, el('span', { textContent: labelOf(h) }), btn)); } } +function renderNuked() { + const { sites, services } = state.nuked; + const without = (obj, key) => Object.fromEntries(Object.entries(obj).filter(([k]) => k !== key)); + renderList('nukedSites', Object.keys(sites), + (h) => save({ nuked: { ...state.nuked, sites: without(sites, h) } }), + (h) => `${h} (${sites[h].length} ${sites[h].length === 1 ? 'thing' : 'things'})`); + renderList('nukedServices', Object.keys(services), + (d) => save({ nuked: { ...state.nuked, services: without(services, d) } }), + (d) => `${services[d].name} (${d})${services[d].from ? `, learned on ${services[d].from}` : ''}`); +} + function render() { $('subtitle').textContent = `Version ${meta.version}, lists built ${fmtDate(meta.builtAt)}`; $('enabled').checked = state.enabled; @@ -61,6 +72,7 @@ function render() { renderCategories(); renderList('pausedList', state.allowlist, (h) => save({ allowlist: state.allowlist.filter((x) => x !== h) })); renderList('unwallList', state.unwallSites, (h) => save({ unwallSites: state.unwallSites.filter((x) => x !== h) })); + renderNuked(); const rows = $('listRows'); rows.replaceChildren(); diff --git a/src/popup/popup.css b/src/popup/popup.css index 2dcc974..1fb6eb6 100644 --- a/src/popup/popup.css +++ b/src/popup/popup.css @@ -32,7 +32,13 @@ body { width: 300px; } .popup[data-level="danger"] { --level: #F07A8E; } } -.actions { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 12px 14px; border-top: 1px solid var(--line); } +.actions { display: flex; flex-direction: column; align-items: stretch; gap: 10px; padding: 12px 14px; border-top: 1px solid var(--line); } +.nuke { width: 100%; } +.nuked { margin: 0; display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 12px; color: var(--muted); } +.nuked[hidden] { display: none; } +.link { padding: 0; border: 0; background: none; color: var(--accent); font: inherit; font-weight: 600; cursor: pointer; } +.link:hover { text-decoration: underline; } +.link[hidden] { display: none; } .check { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); cursor: pointer; } .check input { margin: 0; accent-color: var(--accent); } diff --git a/src/popup/popup.html b/src/popup/popup.html index 77ae397..2248138 100644 --- a/src/popup/popup.html +++ b/src/popup/popup.html @@ -46,8 +46,9 @@
          - - + + +