SPB Git

Repository Public License

reader.js 15.3 KB 311 lines javascript

1// ORIX Navigator — reader article extraction.2// World: orix.reader (isolated). Evaluated on demand as a function body; never installed as a user script.3//4// A readability-style heuristic written for this project:5//   1. score block containers from the paragraphs they hold (length, punctuation), weighted by class/id hints6//      and penalised by link density;7//   2. pick the best container and adopt siblings that look like continuation of the article;8//   3. re-serialise the result by hand into a small tag/attribute allow-list (never `innerHTML` of page nodes),9//      so scripts, event handlers, styles, forms, frames and non-http(s) URLs cannot survive.10// The native side re-validates the returned HTML against the same allow-list before using it.11function __orixReaderExtract(options) {12  "use strict";13  options = options || {};14  var MAX_HTML = options.maxHTMLLength || 2000000;15  var MIN_TEXT = options.minimumTextLength || 200;1617  var UNLIKELY = /(^|[\s_-])(ad|ads|advert\w*|banner|breadcrumbs?|combx|comments?|community|cookie|disqus|extra|footer|gdpr|header|legends?|menu|modal|nav|navigation|newsletter|outbrain|pager|pagination|popup|promo\w*|related|remark|rss|share\w*|shoutbox|sidebar|skyscraper|social|sponsor\w*|subscribe|taboola|toolbar|widget)([\s_-]|$)/i;18  var MAYBE = /(^|[\s_-])(and|article|body|column|content|main|shadow|story|entry|post|text)([\s_-]|$)/i;19  var POSITIVE = /(article|body|content|entry|hentry|h-entry|main|page|post|text|blog|story|prose)/i;20  var NEGATIVE = /(hidden|banner|combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget|newsletter|byline|author|social)/i;21  var SKIP_TAGS = { SCRIPT: 1, STYLE: 1, NOSCRIPT: 1, IFRAME: 1, FRAME: 1, OBJECT: 1, EMBED: 1, FORM: 1, BUTTON: 1, INPUT: 1, SELECT: 1, TEXTAREA: 1, NAV: 1, ASIDE: 1, FOOTER: 1, HEADER: 1, SVG: 1, CANVAS: 1, TEMPLATE: 1, LINK: 1, META: 1, DIALOG: 1, AUDIO: 1, VIDEO: 1, MENU: 1 };22  var KEEP = { P: "p", H1: "h2", H2: "h2", H3: "h3", H4: "h4", H5: "h5", H6: "h6", BLOCKQUOTE: "blockquote", UL: "ul", OL: "ol", LI: "li", PRE: "pre", CODE: "code", EM: "em", I: "em", STRONG: "strong", B: "strong", U: "u", S: "s", SUB: "sub", SUP: "sup", A: "a", IMG: "img", FIGURE: "figure", FIGCAPTION: "figcaption", BR: "br", HR: "hr", TABLE: "table", THEAD: "thead", TBODY: "tbody", TR: "tr", TD: "td", TH: "th", DL: "dl", DT: "dt", DD: "dd", MARK: "mark", Q: "q", CITE: "cite", KBD: "kbd", SMALL: "small" };23  var VOID = { br: 1, hr: 1, img: 1 };24  var BLOCK_CHILDREN = /^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|PRE|TABLE|FIGURE|SECTION|ARTICLE|DL)$/;2526  function text(node) { return (node.textContent || "").replace(/\s+/g, " ").trim(); }27  function signature(el) { return ((el.getAttribute("class") || "") + " " + (el.getAttribute("id") || "")).trim(); }28  function isHidden(el) {29    if (el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true") return true;30    var style = window.getComputedStyle ? window.getComputedStyle(el) : null;31    return !!style && (style.display === "none" || style.visibility === "hidden");32  }33  function linkDensity(el) {34    var total = text(el).length;35    if (!total) return 0;36    var linked = 0;37    var links = el.getElementsByTagName("a");38    for (var i = 0; i < links.length; i++) linked += text(links[i]).length;39    return linked / total;40  }41  function isUnlikely(el) {42    if (SKIP_TAGS[el.tagName]) return true;43    var role = el.getAttribute("role") || "";44    if (/^(navigation|banner|complementary|contentinfo|search|dialog|alert|menu)$/.test(role)) return true;45    var sig = signature(el);46    if (sig && UNLIKELY.test(sig) && !MAYBE.test(sig) && el.tagName !== "BODY" && el.tagName !== "ARTICLE" && el.tagName !== "MAIN") return true;47    return false;48  }49  function insideUnlikely(el, stop) {50    for (var node = el; node && node !== stop && node.nodeType === 1; node = node.parentElement) {51      if (isUnlikely(node)) return true;52    }53    return false;54  }55  function classWeight(el) {56    var weight = 0, sig = signature(el);57    if (sig) {58      if (NEGATIVE.test(sig)) weight -= 25;59      if (POSITIVE.test(sig)) weight += 25;60    }61    return weight;62  }63  function baseScore(el) {64    var score = classWeight(el);65    switch (el.tagName) {66      case "ARTICLE": score += 15; break;67      case "MAIN": score += 8; break;68      case "SECTION": score += 4; break;69      case "DIV": score += 5; break;70      case "PRE": case "TD": case "BLOCKQUOTE": score += 3; break;71      case "ADDRESS": case "OL": case "UL": case "DL": case "DD": case "DT": case "LI": case "FORM": score -= 3; break;72      case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": case "TH": score -= 5; break;73    }74    if (el.getAttribute("itemprop") === "articleBody") score += 30;75    if (el.getAttribute("role") === "main") score += 8;76    return score;77  }7879  var body = document.body;80  if (!body) return { ok: false, reason: "no-body" };8182  // --- 1. Score candidates ---------------------------------------------------------------------------------83  var scores = new Map();84  function credit(el, amount) {85    if (!el || el.nodeType !== 1 || el === document.documentElement) return;86    if (!scores.has(el)) scores.set(el, baseScore(el));87    scores.set(el, scores.get(el) + amount);88  }89  var paragraphs = body.querySelectorAll("p, pre, td, blockquote, li");90  for (var i = 0; i < paragraphs.length; i++) {91    var p = paragraphs[i];92    if (insideUnlikely(p, body) || isHidden(p)) continue;93    var content = text(p);94    if (content.length < 25) continue;95    var points = 1 + (content.match(/[,،,、;:]/g) || []).length + Math.min(Math.floor(content.length / 100), 3);96    if (p.tagName === "LI") points *= 0.5;97    credit(p.parentElement, points);98    if (p.parentElement) {99      credit(p.parentElement.parentElement, points / 2);100      if (p.parentElement.parentElement) credit(p.parentElement.parentElement.parentElement, points / 3);101    }102  }103  // Pages that put text straight into <div>s separated by <br>.104  if (scores.size === 0) {105    var divs = body.querySelectorAll("div, section, article");106    for (var d = 0; d < divs.length; d++) {107      var div = divs[d];108      if (insideUnlikely(div, body) || isHidden(div)) continue;109      var own = "";110      for (var c = div.firstChild; c; c = c.nextSibling) if (c.nodeType === 3) own += c.nodeValue;111      own = own.replace(/\s+/g, " ").trim();112      if (own.length >= 80) credit(div, 1 + Math.min(Math.floor(own.length / 100), 5));113    }114  }115116  var best = null, bestScore = -Infinity;117  scores.forEach(function (score, el) {118    if (el === body && scores.size > 1) score -= 5;119    var adjusted = score * (1 - linkDensity(el));120    scores.set(el, adjusted);121    if (adjusted > bestScore) { best = el; bestScore = adjusted; }122  });123  if (!best) return { ok: false, reason: "no-candidate" };124125  // A lone <article> (or itemprop=articleBody) that contains the winner and is not much larger wins instead:126  // it usually carries the headline and figures the scored <div> misses.127  var semantic = best.closest ? best.closest('article, [itemprop="articleBody"]') : null;128  if (semantic && semantic !== best && !isUnlikely(semantic) && text(semantic).length <= text(best).length * 2.5) {129    best = semantic;130  }131132  // --- 2. Gather the article root and qualifying siblings --------------------------------------------------133  var roots = [];134  var parent = best.parentElement;135  var threshold = Math.max(10, bestScore * 0.2);136  if (parent && parent !== document.documentElement && best !== body) {137    for (var s = parent.firstElementChild; s; s = s.nextElementSibling) {138      if (s === best) { roots.push(s); continue; }139      if (isUnlikely(s) || isHidden(s)) continue;140      var siblingScore = scores.has(s) ? scores.get(s) : -Infinity;141      if (siblingScore >= threshold) { roots.push(s); continue; }142      if (s.tagName === "P") {143        var st = text(s), density = linkDensity(s);144        if ((st.length > 80 && density < 0.25) || (st.length > 0 && st.length <= 80 && density === 0 && /[.!?。]( |$)/.test(st))) roots.push(s);145      }146    }147  } else {148    roots.push(best);149  }150151  // --- 3. Title, byline, language --------------------------------------------------------------------------152  function metaContent(selector) {153    var node = document.querySelector(selector);154    return node ? (node.getAttribute("content") || "").replace(/\s+/g, " ").trim() : "";155  }156  var headline = "";157  for (var r = 0; r < roots.length && !headline; r++) {158    var h1 = roots[r].querySelector("h1");159    if (h1) headline = text(h1);160  }161  var documentTitle = typeof document.title === "string" ? document.title.replace(/\s+/g, " ").trim() : "";162  var title = metaContent('meta[property="og:title"]') || headline;163  if (!title) {164    var anyH1 = document.querySelectorAll("h1");165    if (anyH1.length === 1) title = text(anyH1[0]);166  }167  if (!title) {168    title = documentTitle;169    var parts = title.split(/\s+[|\-–—·»:]\s+/);170    if (parts.length > 1) {171      var longest = parts.reduce(function (a, b) { return b.length > a.length ? b : a; }, "");172      if (longest.split(" ").length >= 3) title = longest;173    }174  }175  title = title.slice(0, 500);176177  function cleanByline(value) {178    value = (value || "").replace(/\s+/g, " ").trim().replace(/^(by|par|von|de|por)\s+/i, "");179    value = value.split(/\s+[·|•]\s+/)[0].trim();180    return value.length > 0 && value.length <= 120 ? value : "";181  }182  var byline = cleanByline(metaContent('meta[name="author"]')) || cleanByline(metaContent('meta[property="article:author"]'));183  if (!byline || /^https?:/i.test(byline)) {184    byline = "";185    var by = document.querySelector('[rel="author"], [itemprop="author"] [itemprop="name"], [itemprop="author"], .byline, .author, .post-author');186    if (by) byline = cleanByline(text(by));187  }188  var language = (document.documentElement.getAttribute("lang") || metaContent('meta[http-equiv="content-language"]') || "").trim().slice(0, 35);189  var published = metaContent('meta[property="article:published_time"]') || metaContent('meta[name="date"]');190  var timeNode = published ? null : document.querySelector("article time[datetime], time[datetime]");191  if (timeNode) published = (timeNode.getAttribute("datetime") || "").trim();192  published = published.slice(0, 64);193194  // --- 4. Sanitising serialiser ----------------------------------------------------------------------------195  function escapeText(value) { return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }196  function escapeAttribute(value) { return escapeText(value).replace(/"/g, "&quot;"); }197  function safeURL(value) {198    if (!value) return "";199    try {200      var url = new URL(value, document.baseURI);201      return (url.protocol === "http:" || url.protocol === "https:") ? url.href : "";202    } catch (e) { return ""; }203  }204  var out = [], outLength = 0, plain = [], truncated = false, imageCount = 0;205  function emit(chunk) {206    if (truncated) return;207    if (outLength + chunk.length > MAX_HTML) { truncated = true; return; }208    out.push(chunk); outLength += chunk.length;209  }210  function isJunk(el, isRoot) {211    if (SKIP_TAGS[el.tagName]) return true;212    if (isRoot) return false;213    if (isHidden(el)) return true;214    var sig = signature(el);215    if (sig && UNLIKELY.test(sig) && !MAYBE.test(sig)) return true;216    if (/^(DIV|SECTION|UL|OL|TABLE)$/.test(el.tagName)) {217      var length = text(el).length;218      if (length > 0 && length < 400 && linkDensity(el) > 0.6 && el.getElementsByTagName("a").length > 2) return true;219    }220    return false;221  }222  function serialise(node, isRoot, inPre) {223    if (truncated) return;224    if (node.nodeType === 3) {225      var value = node.nodeValue || "";226      if (!inPre) value = value.replace(/\s+/g, " ");227      if (value) { emit(escapeText(value)); plain.push(value); }228      return;229    }230    if (node.nodeType !== 1) return;231    var el = node;232    if (isJunk(el, isRoot)) return;233    if (el === skipHeadline) return;234    var tag = KEEP[el.tagName];235    if (el.tagName === "DIV" && !tag) {236      // A <div> holding only inline content is a paragraph in disguise.237      var hasBlock = false;238      for (var k = el.firstElementChild; k; k = k.nextElementSibling) if (BLOCK_CHILDREN.test(k.tagName)) { hasBlock = true; break; }239      if (!hasBlock && text(el).length > 0) tag = "p";240    }241    if (tag === "img") {242      var src = safeURL(el.currentSrc || el.getAttribute("src") || el.getAttribute("data-src") || "");243      if (!src || ++imageCount > 200) return;244      emit('<img src="' + escapeAttribute(src) + '" alt="' + escapeAttribute((el.getAttribute("alt") || "").slice(0, 500)) + '">');245      return;246    }247    if (tag === "br" || tag === "hr") { emit("<" + tag + ">"); plain.push("\n"); return; }248    var open = "";249    if (tag === "a") {250      var href = safeURL(el.getAttribute("href") || "");251      // A link without a safe target degrades to its text.252      if (href) open = '<a href="' + escapeAttribute(href) + '">'; else tag = null;253    } else if (tag === "td" || tag === "th") {254      open = "<" + tag;255      var colspan = parseInt(el.getAttribute("colspan") || "", 10), rowspan = parseInt(el.getAttribute("rowspan") || "", 10);256      if (colspan > 1 && colspan < 100) open += ' colspan="' + colspan + '"';257      if (rowspan > 1 && rowspan < 100) open += ' rowspan="' + rowspan + '"';258      open += ">";259    } else if (tag) {260      open = "<" + tag + ">";261    }262    var mark = out.length, plainMark = plain.length, lengthMark = outLength;263    if (tag) emit(open);264    var pre = inPre || el.tagName === "PRE";265    for (var child = el.firstChild; child; child = child.nextSibling) serialise(child, false, pre);266    if (tag && !VOID[tag]) {267      // Drop wrappers that ended up empty (their content was junk).268      var produced = out.slice(mark + 1).join("");269      if (!truncated && produced.replace(/<[^>]+>/g, "").trim() === "" && produced.indexOf("<img") === -1 && tag !== "td" && tag !== "th") {270        out.length = mark; plain.length = plainMark; outLength = lengthMark;271        return;272      }273      emit("</" + tag + ">");274      if (/^(p|h2|h3|h4|h5|h6|li|blockquote|pre|tr|figcaption|dt|dd)$/.test(tag)) plain.push("\n");275    } else if (!tag && BLOCK_CHILDREN.test(el.tagName)) {276      plain.push("\n");277    }278  }279  // The headline is returned as `title`; do not repeat it at the top of the content.280  var skipHeadline = null;281  for (var q = 0; q < roots.length && !skipHeadline; q++) {282    var candidate = roots[q].querySelector("h1");283    if (candidate && text(candidate) === headline) skipHeadline = candidate;284  }285  for (var n = 0; n < roots.length; n++) serialise(roots[n], true, false);286287  var html = out.join("");288  var textContent = plain.join("").replace(/[ \t\f\v]+/g, " ").replace(/ *\n */g, "\n").replace(/\n{3,}/g, "\n\n").trim();289  if (textContent.length < MIN_TEXT) return { ok: false, reason: "too-short", textLength: textContent.length };290291  var spaced = textContent.split(/\s+/).filter(function (w) { return w.length > 0; });292  var wordCount = spaced.length;293  // Scripts written without spaces: estimate from character count instead.294  var cjk = (textContent.match(/[぀-ヿ㐀-鿿가-힯]/g) || []).length;295  if (cjk > textContent.length * 0.3) wordCount = Math.round(cjk / 2) + spaced.length;296297  return {298    ok: true,299    url: String(location.href).slice(0, 8192),300    title: title,301    byline: byline,302    language: language,303    publishedTime: published,304    contentHTML: html,305    textContent: textContent,306    wordCount: wordCount,307    truncated: truncated,308    score: Math.round(bestScore)309  };310}311
Files main
Menu

Theme