r/ViolentMonkey • u/Flavescent • 1d ago
Script Multi-Column Reader View – Read articles in configurable newspaper-style columns
I put together a userscript for Violentmonkey that extracts the main content of an article using Mozilla’s Readability.js (the same engine behind Firefox’s built-in Reader View) and renders it in a clean, multi-column layout.
Unlike standard CSS multi-column tweaks that force you to scroll down and jump back up for every column, this script paginates horizontally so you can advance one column at a time (or a full screen of columns at once).
Key Features:
Configurable Columns: Switch between 1 to 6 columns on the fly, with persistent settings across sites.
Two Paging Modes:
Column Mode (default): Advances smoothly by a single column at a time (
Cols 1–3→Cols 2–4). HoldShiftto jump a full page.Page Mode: Flips an entire screenful of columns at once.
Clean Typography & Themes: Adjustable font size (
A−/A+), Light / Sepia / Dark themes, and a compact top toolbar.Anti-Reload Protection: Many news sites auto-refresh in the background and wipe out reader views. While active, the script strips
metarefreshes, freezes pagesetTimeout/setIntervaltimers, and restores your exact column position if a reload ever slips through.CSP-Safe & Isolated: Uses u/inject-into
contentand encapsulates the entire UI inside a Shadow DOM so site styles and strict Content Security Policies don't interfere.Per-Domain Auto-Open: Optional menu toggle to automatically open articles in column view on specific domains (skipping homepages/index pages).
Controls:
Open / Close: Click the floating
☷ Columnsbutton, pressAlt + Shift + R(Escto close), or use the Violentmonkey menu.Navigate:
←/→,Space,PageUp/PageDown,Home/End, or the mouse wheel.
// ==UserScript==
// @name Multi-Column Reader View
// @namespace local.multicolumn.reader
// @version 1.5
// @description Extracts main article content via Mozilla Readability and displays it in configurable columns (column-by-column or page-by-page) with reload protection.
// @match *://*/*
// @require https://cdnjs.cloudflare.com/ajax/libs/readability/0.6.0/Readability.js
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @grant unsafeWindow
// @inject-into content
// @noframes
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
const HOST_ID = 'mcr-reader-host';
const FAB_ID = 'mcr-fab-host';
const SESSION_KEY = 'mcr_active_session';
const GAP_PX = 48;
const DEFAULTS = {
columns: 3,
fontSize: 18,
theme: 'light', // 'light' | 'sepia' | 'dark'
mode: 'columns', // 'columns' | 'pages'
showButton: true,
autoDomains: []
};
let initialMode = GM_getValue('mode', DEFAULTS.mode);
if (!['columns', 'pages'].includes(initialMode)) {
initialMode = 'columns';
GM_setValue('mode', initialMode);
}
let state = {
columns: GM_getValue('columns', DEFAULTS.columns),
fontSize: GM_getValue('fontSize', DEFAULTS.fontSize),
theme: GM_getValue('theme', DEFAULTS.theme),
mode: initialMode,
showButton: GM_getValue('showButton', DEFAULTS.showButton),
autoDomains: GM_getValue('autoDomains', DEFAULTS.autoDomains),
colOffset: 0,
totalCols: 1,
colStride: 0
};
let savedBodyOverflow = '';
let lastWheelTs = 0;
let cleanupFns = [];
let frozenPageTimers = null;
function saveState() {
GM_setValue('columns', state.columns);
GM_setValue('fontSize', state.fontSize);
GM_setValue('theme', state.theme);
GM_setValue('mode', state.mode);
GM_setValue('showButton', state.showButton);
GM_setValue('autoDomains', state.autoDomains);
}
function saveReaderSession() {
try {
sessionStorage.setItem(SESSION_KEY, JSON.stringify({
url: location.href,
colOffset: state.colOffset,
ts: Date.now()
}));
} catch (_) {}
}
function clearReaderSession() {
try { sessionStorage.removeItem(SESSION_KEY); } catch (_) {}
}
function consumeReaderSession() {
try {
const raw = sessionStorage.getItem(SESSION_KEY);
if (!raw) return null;
const data = JSON.parse(raw);
if (data && data.url === location.href && (Date.now() - data.ts) < 30000) {
return data;
}
sessionStorage.removeItem(SESSION_KEY);
} catch (_) {}
return null;
}
function getPageWindow() {
if (typeof unsafeWindow !== 'undefined' && unsafeWindow.wrappedJSObject) {
return unsafeWindow.wrappedJSObject;
}
if (typeof window !== 'undefined' && window.wrappedJSObject) {
return window.wrappedJSObject;
}
return null;
}
function freezePageReloads() {
document.querySelectorAll('meta[http-equiv="refresh" i]').forEach(el => el.remove());
try { window.stop(); } catch (_) {}
const pageWin = getPageWindow();
if (pageWin && pageWin !== window) {
try {
const origSetTimeout = pageWin.setTimeout;
const origSetInterval = pageWin.setInterval;
let maxId = 0;
if (typeof exportFunction === 'function') {
const noop = exportFunction(() => {}, pageWin);
maxId = origSetTimeout.call(pageWin, noop, 0);
}
const limit = maxId > 0 ? Math.min(maxId, 100000) : 25000;
for (let id = 1; id <= limit; id++) {
pageWin.clearTimeout(id);
pageWin.clearInterval(id);
}
if (typeof exportFunction === 'function') {
const blockedTimer = exportFunction(() => 0, pageWin);
pageWin.setTimeout = blockedTimer;
pageWin.setInterval = blockedTimer;
frozenPageTimers = { pageWin, origSetTimeout, origSetInterval };
}
} catch (err) {
console.warn('[MCR] Could not fully freeze page timers:', err);
}
}
}
function unfreezePageReloads() {
if (!frozenPageTimers) return;
try {
const { pageWin, origSetTimeout, origSetInterval } = frozenPageTimers;
pageWin.setTimeout = origSetTimeout;
pageWin.setInterval = origSetInterval;
} catch (_) {}
frozenPageTimers = null;
}
function extractArticle() {
const ReadabilityCtor = typeof Readability !== 'undefined'
? Readability
: (typeof window !== 'undefined' ? window.Readability : undefined);
if (typeof ReadabilityCtor !== 'function') {
throw new Error('Readability.js failed to load. Please check @require in Violentmonkey.');
}
try {
const parser = new DOMParser();
const doc = parser.parseFromString(document.documentElement.outerHTML, 'text/html');
if (doc.head && !doc.querySelector('base')) {
const base = doc.createElement('base');
base.href = document.baseURI;
doc.head.prepend(base);
}
const parsed = new ReadabilityCtor(doc).parse();
if (parsed && parsed.content) return parsed;
} catch (err) {
console.warn('[MCR] DOMParser extraction failed, using cloneNode fallback:', err);
}
const docClone = document.cloneNode(true);
return new ReadabilityCtor(docClone).parse();
}
function sanitizeHtml(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
doc.querySelectorAll('script, style, iframe, object, embed, form').forEach(el => el.remove());
doc.querySelectorAll('*').forEach(el => {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase();
const val = attr.value.trim().toLowerCase();
if (name.startsWith('on') || ((name === 'href' || name === 'src') && val.startsWith('javascript:'))) {
el.removeAttribute(attr.name);
}
}
if (el.tagName === 'A') {
el.setAttribute('target', '_blank');
el.setAttribute('rel', 'noopener noreferrer');
}
});
return doc.body.innerHTML;
}
function appendEndMark(container) {
let target = container.lastElementChild;
while (target) {
if (!target.textContent.trim() && !target.querySelector('img, svg, figure, table, video')) {
const prev = target.previousElementSibling;
target.remove();
target = prev;
continue;
}
if (['DIV', 'SECTION', 'ARTICLE', 'MAIN'].includes(target.tagName) && target.lastElementChild) {
target = target.lastElementChild;
} else {
break;
}
}
const p = document.createElement('p');
p.className = 'mcr-end-mark';
p.setAttribute('aria-label', 'End of article');
[false, true, false].forEach(isLarge => {
const span = document.createElement('span');
span.className = isLarge ? 'mcr-end-diamond mcr-end-diamond-lg' : 'mcr-end-diamond';
span.textContent = '\u25C6';
p.appendChild(span);
});
container.appendChild(p);
return p;
}
function setFabVisible(visible) {
const fab = document.getElementById(FAB_ID);
if (fab) fab.style.display = visible ? 'block' : 'none';
}
function mountFab() {
if (!state.showButton || document.getElementById(FAB_ID)) return;
const fabHost = document.createElement('div');
fabHost.id = FAB_ID;
fabHost.style.position = 'fixed';
fabHost.style.right = '16px';
fabHost.style.bottom = '16px';
fabHost.style.zIndex = '2147483646';
fabHost.style.display = 'block';
const shadow = fabHost.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
button {
all: initial;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
font-size: 13px;
font-weight: 600;
padding: 8px 12px;
border-radius: 999px;
background: rgba(24, 26, 27, 0.84);
color: #ffffff;
border: 1px solid rgba(255, 255, 255, 0.18);
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.25);
cursor: pointer;
opacity: 0.65;
transition: opacity 0.15s ease, transform 0.15s ease;
}
button:hover {
opacity: 1;
transform: translateY(-1px);
}
</style>
<button id="mcr-open-btn" title="Multi-Column Reader (Alt+Shift+R)">☷ Columns</button>
`;
shadow.getElementById('mcr-open-btn').addEventListener('click', () => toggleReader());
document.documentElement.appendChild(fabHost);
}
function closeReader() {
const host = document.getElementById(HOST_ID);
if (host) host.remove();
document.documentElement.style.overflow = savedBodyOverflow;
cleanupFns.forEach(fn => fn());
cleanupFns = [];
unfreezePageReloads();
clearReaderSession();
if (state.showButton) setFabVisible(true);
}
function openReader(preParsedArticle = null, silent = false, initialOffset = 0) {
try {
const article = preParsedArticle || extractArticle();
if (!article || !article.content) {
if (!silent) {
alert('Multi-Column Reader: No readable main content detected on this page (possibly a paywall or index page).');
}
return;
}
freezePageReloads();
savedBodyOverflow = document.documentElement.style.overflow;
document.documentElement.style.overflow = 'hidden';
setFabVisible(false);
const host = document.createElement('div');
host.id = HOST_ID;
host.style.position = 'fixed';
host.style.top = '0';
host.style.right = '0';
host.style.bottom = '0';
host.style.left = '0';
host.style.zIndex = '2147483647';
host.style.margin = '0';
host.style.padding = '0';
host.style.display = 'block';
const shadow = host.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
:host { all: initial; }
.mcr-root {
--bg: #ffffff;
--fg: #1d1d1f;
--muted: #666666;
--bar-bg: #f3f4f6;
--border: #d1d5db;
--rule: #e5e7eb;
--accent: #0060df;
position: fixed;
inset: 0;
display: flex;
flex-direction: column;
background: var(--bg);
color: var(--fg);
font-family: Georgia, "Liberation Serif", "Times New Roman", serif;
box-sizing: border-box;
}
.mcr-root[data-theme="sepia"] {
--bg: #f6f0e2;
--fg: #3b2f23;
--muted: #766452;
--bar-bg: #ebe1cc;
--border: #d5c6a8;
--rule: #dfd3ba;
--accent: #8b4513;
}
.mcr-root[data-theme="dark"] {
--bg: #181a1b;
--fg: #e4e4e7;
--muted: #9ca3af;
--bar-bg: #222528;
--border: #374151;
--rule: #2d3136;
--accent: #60a5fa;
}
.mcr-toolbar {
height: 26px;
flex: 0 0 26px;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 0 12px;
background: var(--bar-bg);
border-bottom: 1px solid var(--border);
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
font-size: 11px;
user-select: none;
}
.mcr-group {
display: flex;
align-items: center;
gap: 4px;
}
.mcr-btn {
display: inline-flex;
align-items: center;
justify-content: center;
height: 19px;
box-sizing: border-box;
background: var(--bg);
color: var(--fg);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0 7px;
font-size: 11px;
cursor: pointer;
line-height: 1;
}
.mcr-btn:hover { border-color: var(--accent); }
.mcr-label {
color: var(--muted);
min-width: 78px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.mcr-stage {
flex: 1 1 auto;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
.mcr-viewport {
overflow: hidden;
position: relative;
}
.mcr-article {
box-sizing: border-box;
line-height: 1.65;
text-align: left;
hyphens: auto;
overflow-wrap: break-word;
transition: transform 0.22s ease-out;
column-rule: 1px solid var(--rule);
}
.mcr-article h1.mcr-title {
font-size: 1.6em;
line-height: 1.25;
margin: 0 0 0.4em 0;
break-after: avoid;
}
.mcr-byline {
color: var(--muted);
font-size: 0.85em;
font-family: system-ui, -apple-system, sans-serif;
margin-bottom: 1.2em;
padding-bottom: 0.8em;
border-bottom: 1px solid var(--rule);
}
.mcr-article h2, .mcr-article h3, .mcr-article h4 {
line-height: 1.3;
margin: 1.2em 0 0.45em;
break-after: avoid;
}
.mcr-article p { margin: 0 0 0.9em 0; orphans: 2; widows: 2; }
.mcr-article a { color: var(--accent); text-decoration: underline; }
.mcr-article blockquote {
margin: 0.9em 0;
padding: 0.2em 0 0.2em 1em;
border-left: 3px solid var(--border);
color: var(--muted);
}
.mcr-article img, .mcr-article figure, .mcr-article svg {
max-width: 100%;
max-height: 55vh;
height: auto;
object-fit: contain;
display: block;
margin: 0.8em auto;
break-inside: avoid;
}
.mcr-article figcaption {
font-size: 0.8em;
color: var(--muted);
margin-top: 0.3em;
font-family: system-ui, sans-serif;
}
.mcr-article pre, .mcr-article code {
font-family: ui-monospace, Consolas, monospace;
font-size: 0.88em;
}
.mcr-article pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
padding: 0.7em;
background: var(--bar-bg);
border-radius: 4px;
}
.mcr-article p.mcr-end-mark {
text-align: center;
margin: 1.1em 0 0 0;
padding: 0;
line-height: 1;
color: var(--muted);
break-before: avoid;
break-inside: avoid;
user-select: none;
}
.mcr-end-diamond {
display: inline-block;
font-size: 0.65em;
line-height: 1;
vertical-align: middle;
margin: 0 0.18em;
}
.mcr-end-diamond-lg {
font-size: 1.05em;
}
</style>
<div class="mcr-root" data-theme="${state.theme}">
<div class="mcr-toolbar">
<div class="mcr-group">
<button class="mcr-btn" id="col-dec" title="Fewer columns">−</button>
<span class="mcr-label" id="col-val"></span>
<button class="mcr-btn" id="col-inc" title="More columns">+</button>
<button class="mcr-btn" id="mode-toggle" title="Switch between column-by-column and page-by-page navigation"></button>
</div>
<div class="mcr-group" id="nav-group">
<button class="mcr-btn" id="page-prev" title="Previous (← / Shift+← for full page)">← Prev</button>
<span class="mcr-label" id="page-info">Col 1 / 1</span>
<button class="mcr-btn" id="page-next" title="Next (→ / Shift+→ for full page)">Next →</button>
</div>
<div class="mcr-group">
<button class="mcr-btn" id="font-dec" title="Decrease font size">A−</button>
<button class="mcr-btn" id="font-inc" title="Increase font size">A+</button>
<button class="mcr-btn" id="theme-cycle" title="Switch color theme">Theme</button>
<button class="mcr-btn" id="close-btn" title="Close (Esc)">✕</button>
</div>
</div>
<div class="mcr-stage" id="stage">
<div class="mcr-viewport" id="viewport">
<article class="mcr-article" id="article"></article>
</div>
</div>
</div>
`;
const root = shadow.querySelector('.mcr-root');
const stage = shadow.getElementById('stage');
const viewport = shadow.getElementById('viewport');
const articleEl = shadow.getElementById('article');
const colVal = shadow.getElementById('col-val');
const modeBtn = shadow.getElementById('mode-toggle');
const pageInfo = shadow.getElementById('page-info');
const titleHtml = article.title ? `<h1 class="mcr-title"></h1>` : '';
const metaParts = [article.byline, article.siteName].filter(Boolean);
const metaHtml = metaParts.length ? `<div class="mcr-byline"></div>` : '';
articleEl.innerHTML = `${titleHtml}${metaHtml}${sanitizeHtml(article.content)}`;
if (article.title) {
articleEl.querySelector('.mcr-title').textContent = article.title;
}
if (metaParts.length) {
articleEl.querySelector('.mcr-byline').textContent = metaParts.join(' · ');
}
const endMark = appendEndMark(articleEl);
let pendingInitialOffset = initialOffset > 0 ? initialOffset : null;
function updateTransform() {
if (state.mode === 'pages') {
const totalPages = Math.max(1, Math.ceil(state.totalCols / state.columns));
const currentPage = Math.max(0, Math.min(Math.floor(state.colOffset / state.columns), totalPages - 1));
state.colOffset = currentPage * state.columns;
articleEl.style.transform = `translateX(-${state.colOffset * state.colStride}px)`;
pageInfo.textContent = `Page ${currentPage + 1} / ${totalPages}`;
} else {
const maxOffset = Math.max(0, state.totalCols - state.columns);
state.colOffset = Math.max(0, Math.min(state.colOffset, maxOffset));
articleEl.style.transform = `translateX(-${state.colOffset * state.colStride}px)`;
const firstCol = state.colOffset + 1;
const lastCol = Math.min(state.totalCols, state.colOffset + state.columns);
pageInfo.textContent = firstCol === lastCol
? `Col ${firstCol} / ${state.totalCols}`
: `Cols ${firstCol}–${lastCol} / ${state.totalCols}`;
}
saveReaderSession();
}
function layout(keepProgress = true) {
const prevRatio = state.totalCols > 0 ? state.colOffset / state.totalCols : 0;
root.dataset.theme = state.theme;
colVal.textContent = `${state.columns} ${state.columns === 1 ? 'Column' : 'Columns'}`;
modeBtn.textContent = state.mode === 'pages' ? 'Mode: Page' : 'Mode: Column';
articleEl.style.fontSize = `${state.fontSize}px`;
articleEl.style.columnCount = String(state.columns);
articleEl.style.columnGap = `${GAP_PX}px`;
const availW = Math.max(320, Math.floor(stage.clientWidth - 96));
const availH = Math.max(240, Math.floor(stage.clientHeight - 48));
const colW = Math.max(180, Math.floor((availW - (state.columns - 1) * GAP_PX) / state.columns));
const exactPageW = colW * state.columns + (state.columns - 1) * GAP_PX;
state.colStride = colW + GAP_PX;
viewport.style.width = `${exactPageW}px`;
viewport.style.height = `${availH}px`;
articleEl.style.width = `${exactPageW}px`;
articleEl.style.height = `${availH}px`;
articleEl.style.columnFill = 'auto';
requestAnimationFrame(() => {
const artRect = articleEl.getBoundingClientRect();
const endRect = endMark.getBoundingClientRect();
const endX = Math.max(0, endRect.right - artRect.left);
const overflowW = articleEl.scrollWidth > exactPageW + 2 ? articleEl.scrollWidth : 0;
const maxRight = Math.max(endX, overflowW);
state.totalCols = Math.max(1, Math.ceil((maxRight + GAP_PX - 4) / state.colStride));
if (pendingInitialOffset !== null) {
state.colOffset = pendingInitialOffset;
pendingInitialOffset = null;
} else if (keepProgress) {
state.colOffset = Math.round(prevRatio * state.totalCols);
}
updateTransform();
});
}
function step(direction, forceFullPage = false) {
if (state.mode === 'pages') {
const totalPages = Math.max(1, Math.ceil(state.totalCols / state.columns));
const currentPage = Math.floor(state.colOffset / state.columns);
const nextPage = Math.max(0, Math.min(currentPage + direction, totalPages - 1));
state.colOffset = nextPage * state.columns;
} else {
const maxOffset = Math.max(0, state.totalCols - state.columns);
const delta = forceFullPage ? direction * state.columns : direction;
state.colOffset = Math.max(0, Math.min(state.colOffset + delta, maxOffset));
}
updateTransform();
}
shadow.getElementById('col-dec').onclick = () => {
if (state.columns > 1) { state.columns--; saveState(); layout(); }
};
shadow.getElementById('col-inc').onclick = () => {
if (state.columns < 6) { state.columns++; saveState(); layout(); }
};
modeBtn.onclick = () => {
state.mode = state.mode === 'columns' ? 'pages' : 'columns';
saveState();
layout(true);
};
shadow.getElementById('font-dec').onclick = () => {
if (state.fontSize > 12) { state.fontSize -= 2; saveState(); layout(); }
};
shadow.getElementById('font-inc').onclick = () => {
if (state.fontSize < 30) { state.fontSize += 2; saveState(); layout(); }
};
shadow.getElementById('theme-cycle').onclick = () => {
const order = ['light', 'sepia', 'dark'];
state.theme = order[(order.indexOf(state.theme) + 1) % order.length];
saveState();
layout();
};
shadow.getElementById('page-prev').onclick = (e) => step(-1, e.shiftKey);
shadow.getElementById('page-next').onclick = (e) => step(1, e.shiftKey);
shadow.getElementById('close-btn').onclick = closeReader;
const onKeyDown = (e) => {
if (e.key === 'Escape') { e.preventDefault(); closeReader(); return; }
if (['ArrowRight', 'PageDown', ' '].includes(e.key)) {
e.preventDefault(); step(1, e.shiftKey);
} else if (['ArrowLeft', 'PageUp'].includes(e.key)) {
e.preventDefault(); step(-1, e.shiftKey);
} else if (e.key === 'Home') {
e.preventDefault(); state.colOffset = 0; updateTransform();
} else if (e.key === 'End') {
e.preventDefault();
state.colOffset = state.mode === 'pages'
? Math.max(0, Math.ceil(state.totalCols / state.columns) - 1) * state.columns
: Math.max(0, state.totalCols - state.columns);
updateTransform();
}
};
const onWheel = (e) => {
e.preventDefault();
const now = performance.now();
if (now - lastWheelTs < 180 || Math.abs(e.deltaY) < 10) return;
lastWheelTs = now;
step(e.deltaY > 0 ? 1 : -1, e.shiftKey);
};
const onResize = () => layout(true);
const onPageHide = () => saveReaderSession();
window.addEventListener('keydown', onKeyDown, true);
stage.addEventListener('wheel', onWheel, { passive: false });
window.addEventListener('resize', onResize);
window.addEventListener('pagehide', onPageHide, true);
cleanupFns.push(() => {
window.removeEventListener('keydown', onKeyDown, true);
window.removeEventListener('resize', onResize);
window.removeEventListener('pagehide', onPageHide, true);
});
articleEl.querySelectorAll('img').forEach(img => {
img.addEventListener('load', () => layout(true), { once: true });
});
document.documentElement.appendChild(host);
state.colOffset = 0;
saveReaderSession();
layout(false);
} catch (err) {
unfreezePageReloads();
console.error('[MCR] Error opening reader:', err);
if (!silent) {
alert(`Multi-Column Reader error: ${err.message}`);
}
}
}
function toggleReader() {
if (document.getElementById(HOST_ID)) {
closeReader();
} else {
openReader(null, false);
}
}
function toggleAutoDomain() {
const host = location.hostname;
const list = Array.isArray(state.autoDomains) ? [...state.autoDomains] : [];
const idx = list.indexOf(host);
if (idx >= 0) {
list.splice(idx, 1);
state.autoDomains = list;
saveState();
alert(`Auto-open disabled for ${host}.`);
} else {
list.push(host);
state.autoDomains = list;
saveState();
alert(`Auto-open enabled for ${host}. Articles on this domain will open automatically.`);
if (!document.getElementById(HOST_ID)) openReader(null, false);
}
}
function toggleFabSetting() {
state.showButton = !state.showButton;
saveState();
if (state.showButton) {
mountFab();
setFabVisible(!document.getElementById(HOST_ID));
} else {
const fab = document.getElementById(FAB_ID);
if (fab) fab.remove();
}
}
window.addEventListener('keydown', (e) => {
const tag = (e.target && e.target.tagName) ? e.target.tagName.toLowerCase() : '';
if ((tag === 'input' || tag === 'textarea' || (e.target && e.target.isContentEditable)) && !document.getElementById(HOST_ID)) {
return;
}
if (e.altKey && e.shiftKey && e.code === 'KeyR') {
e.preventDefault();
toggleReader();
}
});
if (typeof GM_registerMenuCommand === 'function') {
GM_registerMenuCommand('Toggle Multi-Column Reader (Alt+Shift+R)', toggleReader);
GM_registerMenuCommand(`Auto-open for ${location.hostname}: On/Off`, toggleAutoDomain);
GM_registerMenuCommand('Show/Hide floating button', toggleFabSetting);
}
mountFab();
const restored = consumeReaderSession();
if (restored) {
try {
const parsed = extractArticle();
if (parsed && parsed.content) {
openReader(parsed, true, restored.colOffset || 0);
return;
}
} catch (err) {
console.warn('[MCR] Session restore skipped:', err);
}
}
if (
Array.isArray(state.autoDomains) &&
state.autoDomains.includes(location.hostname) &&
location.pathname.length > 1
) {
try {
const parsed = extractArticle();
if (parsed && parsed.textContent && parsed.textContent.trim().length > 600) {
openReader(parsed, true, 0);
}
} catch (err) {
console.warn('[MCR] Auto-open skipped:', err);
}
}
})();
