Readability.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. /*eslint-env es6:false*/
  2. /*
  3. * Copyright (c) 2010 Arc90 Inc
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * This code is heavily based on Arc90's readability.js (1.7.1) script
  19. * available at: http://code.google.com/p/arc90labs-readability
  20. */
  21. /**
  22. * Public constructor.
  23. * @param {HTMLDocument} doc The document to parse.
  24. * @param {Object} options The options object.
  25. */
  26. function Readability(doc, options) {
  27. // In some older versions, people passed a URI as the first argument. Cope:
  28. if (options && options.documentElement) {
  29. doc = options;
  30. options = arguments[2];
  31. } else if (!doc || !doc.documentElement) {
  32. throw new Error("First argument to Readability constructor should be a document object.");
  33. }
  34. options = options || {};
  35. this._doc = doc;
  36. this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__;
  37. this._articleTitle = null;
  38. this._articleByline = null;
  39. this._articleDir = null;
  40. this._articleSiteName = null;
  41. this._attempts = [];
  42. // Configurable options
  43. this._debug = !!options.debug;
  44. this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE;
  45. this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES;
  46. this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD;
  47. this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []);
  48. this._keepClasses = !!options.keepClasses;
  49. // Start with all flags set
  50. this._flags = this.FLAG_STRIP_UNLIKELYS |
  51. this.FLAG_WEIGHT_CLASSES |
  52. this.FLAG_CLEAN_CONDITIONALLY;
  53. var logEl;
  54. // Control whether log messages are sent to the console
  55. if (this._debug) {
  56. logEl = function(e) {
  57. var rv = e.nodeName + " ";
  58. if (e.nodeType == e.TEXT_NODE) {
  59. return rv + '("' + e.textContent + '")';
  60. }
  61. var classDesc = e.className && ("." + e.className.replace(/ /g, "."));
  62. var elDesc = "";
  63. if (e.id)
  64. elDesc = "(#" + e.id + classDesc + ")";
  65. else if (classDesc)
  66. elDesc = "(" + classDesc + ")";
  67. return rv + elDesc;
  68. };
  69. this.log = function () {
  70. if (typeof dump !== "undefined") {
  71. var msg = Array.prototype.map.call(arguments, function(x) {
  72. return (x && x.nodeName) ? logEl(x) : x;
  73. }).join(" ");
  74. dump("Reader: (Readability) " + msg + "\n");
  75. } else if (typeof console !== "undefined") {
  76. var args = ["Reader: (Readability) "].concat(arguments);
  77. console.log.apply(console, args);
  78. }
  79. };
  80. } else {
  81. this.log = function () {};
  82. }
  83. }
  84. Readability.prototype = {
  85. FLAG_STRIP_UNLIKELYS: 0x1,
  86. FLAG_WEIGHT_CLASSES: 0x2,
  87. FLAG_CLEAN_CONDITIONALLY: 0x4,
  88. // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
  89. ELEMENT_NODE: 1,
  90. TEXT_NODE: 3,
  91. // Max number of nodes supported by this parser. Default: 0 (no limit)
  92. DEFAULT_MAX_ELEMS_TO_PARSE: 0,
  93. // The number of top candidates to consider when analysing how
  94. // tight the competition is among candidates.
  95. DEFAULT_N_TOP_CANDIDATES: 5,
  96. // Element tags to score by default.
  97. DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","),
  98. // The default number of chars an article must have in order to return a result
  99. DEFAULT_CHAR_THRESHOLD: 500,
  100. // All of the regular expressions in use within readability.
  101. // Defined up here so we don't instantiate them repeatedly in loops.
  102. REGEXPS: {
  103. // NOTE: These two regular expressions are duplicated in
  104. // Readability-readerable.js. Please keep both copies in sync.
  105. unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,
  106. okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i,
  107. positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,
  108. negative: /hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i,
  109. extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,
  110. byline: /byline|author|dateline|writtenby|p-author/i,
  111. replaceFonts: /<(\/?)font[^>]*>/gi,
  112. normalize: /\s{2,}/g,
  113. videos: /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,
  114. shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i,
  115. nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,
  116. prevLink: /(prev|earl|old|new|<|«)/i,
  117. whitespace: /^\s*$/,
  118. hasContent: /\S$/,
  119. },
  120. DIV_TO_P_ELEMS: [ "A", "BLOCKQUOTE", "DL", "DIV", "IMG", "OL", "P", "PRE", "TABLE", "UL", "SELECT" ],
  121. ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P"],
  122. PRESENTATIONAL_ATTRIBUTES: [ "align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace" ],
  123. DEPRECATED_SIZE_ATTRIBUTE_ELEMS: [ "TABLE", "TH", "TD", "HR", "PRE" ],
  124. // The commented out elements qualify as phrasing content but tend to be
  125. // removed by readability when put into paragraphs, so we ignore them here.
  126. PHRASING_ELEMS: [
  127. // "CANVAS", "IFRAME", "SVG", "VIDEO",
  128. "ABBR", "AUDIO", "B", "BDO", "BR", "BUTTON", "CITE", "CODE", "DATA",
  129. "DATALIST", "DFN", "EM", "EMBED", "I", "IMG", "INPUT", "KBD", "LABEL",
  130. "MARK", "MATH", "METER", "NOSCRIPT", "OBJECT", "OUTPUT", "PROGRESS", "Q",
  131. "RUBY", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRONG", "SUB",
  132. "SUP", "TEXTAREA", "TIME", "VAR", "WBR"
  133. ],
  134. // These are the classes that readability sets itself.
  135. CLASSES_TO_PRESERVE: [ "page" ],
  136. /**
  137. * Run any post-process modifications to article content as necessary.
  138. *
  139. * @param Element
  140. * @return void
  141. **/
  142. _postProcessContent: function(articleContent) {
  143. // Readability cannot open relative uris so we convert them to absolute uris.
  144. this._fixRelativeUris(articleContent);
  145. if (!this._keepClasses) {
  146. // Remove classes.
  147. this._cleanClasses(articleContent);
  148. }
  149. },
  150. /**
  151. * Iterates over a NodeList, calls `filterFn` for each node and removes node
  152. * if function returned `true`.
  153. *
  154. * If function is not passed, removes all the nodes in node list.
  155. *
  156. * @param NodeList nodeList The nodes to operate on
  157. * @param Function filterFn the function to use as a filter
  158. * @return void
  159. */
  160. _removeNodes: function(nodeList, filterFn) {
  161. // Avoid ever operating on live node lists.
  162. if (this._docJSDOMParser && nodeList._isLiveNodeList) {
  163. throw new Error("Do not pass live node lists to _removeNodes");
  164. }
  165. for (var i = nodeList.length - 1; i >= 0; i--) {
  166. var node = nodeList[i];
  167. var parentNode = node.parentNode;
  168. if (parentNode) {
  169. if (!filterFn || filterFn.call(this, node, i, nodeList)) {
  170. parentNode.removeChild(node);
  171. }
  172. }
  173. }
  174. },
  175. /**
  176. * Iterates over a NodeList, and calls _setNodeTag for each node.
  177. *
  178. * @param NodeList nodeList The nodes to operate on
  179. * @param String newTagName the new tag name to use
  180. * @return void
  181. */
  182. _replaceNodeTags: function(nodeList, newTagName) {
  183. // Avoid ever operating on live node lists.
  184. if (this._docJSDOMParser && nodeList._isLiveNodeList) {
  185. throw new Error("Do not pass live node lists to _replaceNodeTags");
  186. }
  187. for (var i = nodeList.length - 1; i >= 0; i--) {
  188. var node = nodeList[i];
  189. this._setNodeTag(node, newTagName);
  190. }
  191. },
  192. /**
  193. * Iterate over a NodeList, which doesn't natively fully implement the Array
  194. * interface.
  195. *
  196. * For convenience, the current object context is applied to the provided
  197. * iterate function.
  198. *
  199. * @param NodeList nodeList The NodeList.
  200. * @param Function fn The iterate function.
  201. * @return void
  202. */
  203. _forEachNode: function(nodeList, fn) {
  204. Array.prototype.forEach.call(nodeList, fn, this);
  205. },
  206. /**
  207. * Iterate over a NodeList, return true if any of the provided iterate
  208. * function calls returns true, false otherwise.
  209. *
  210. * For convenience, the current object context is applied to the
  211. * provided iterate function.
  212. *
  213. * @param NodeList nodeList The NodeList.
  214. * @param Function fn The iterate function.
  215. * @return Boolean
  216. */
  217. _someNode: function(nodeList, fn) {
  218. return Array.prototype.some.call(nodeList, fn, this);
  219. },
  220. /**
  221. * Iterate over a NodeList, return true if all of the provided iterate
  222. * function calls return true, false otherwise.
  223. *
  224. * For convenience, the current object context is applied to the
  225. * provided iterate function.
  226. *
  227. * @param NodeList nodeList The NodeList.
  228. * @param Function fn The iterate function.
  229. * @return Boolean
  230. */
  231. _everyNode: function(nodeList, fn) {
  232. return Array.prototype.every.call(nodeList, fn, this);
  233. },
  234. /**
  235. * Concat all nodelists passed as arguments.
  236. *
  237. * @return ...NodeList
  238. * @return Array
  239. */
  240. _concatNodeLists: function() {
  241. var slice = Array.prototype.slice;
  242. var args = slice.call(arguments);
  243. var nodeLists = args.map(function(list) {
  244. return slice.call(list);
  245. });
  246. return Array.prototype.concat.apply([], nodeLists);
  247. },
  248. _getAllNodesWithTag: function(node, tagNames) {
  249. if (node.querySelectorAll) {
  250. return node.querySelectorAll(tagNames.join(","));
  251. }
  252. return [].concat.apply([], tagNames.map(function(tag) {
  253. var collection = node.getElementsByTagName(tag);
  254. return Array.isArray(collection) ? collection : Array.from(collection);
  255. }));
  256. },
  257. /**
  258. * Removes the class="" attribute from every element in the given
  259. * subtree, except those that match CLASSES_TO_PRESERVE and
  260. * the classesToPreserve array from the options object.
  261. *
  262. * @param Element
  263. * @return void
  264. */
  265. _cleanClasses: function(node) {
  266. var classesToPreserve = this._classesToPreserve;
  267. var className = (node.getAttribute("class") || "")
  268. .split(/\s+/)
  269. .filter(function(cls) {
  270. return classesToPreserve.indexOf(cls) != -1;
  271. })
  272. .join(" ");
  273. if (className) {
  274. node.setAttribute("class", className);
  275. } else {
  276. node.removeAttribute("class");
  277. }
  278. for (node = node.firstElementChild; node; node = node.nextElementSibling) {
  279. this._cleanClasses(node);
  280. }
  281. },
  282. /**
  283. * Converts each <a> and <img> uri in the given element to an absolute URI,
  284. * ignoring #ref URIs.
  285. *
  286. * @param Element
  287. * @return void
  288. */
  289. _fixRelativeUris: function(articleContent) {
  290. var baseURI = this._doc.baseURI;
  291. var documentURI = this._doc.documentURI;
  292. function toAbsoluteURI(uri) {
  293. // Leave hash links alone if the base URI matches the document URI:
  294. if (baseURI == documentURI && uri.charAt(0) == "#") {
  295. return uri;
  296. }
  297. // Otherwise, resolve against base URI:
  298. try {
  299. return new URL(uri, baseURI).href;
  300. } catch (ex) {
  301. // Something went wrong, just return the original:
  302. }
  303. return uri;
  304. }
  305. var links = this._getAllNodesWithTag(articleContent, ["a"]);
  306. this._forEachNode(links, function(link) {
  307. var href = link.getAttribute("href");
  308. if (href) {
  309. // Remove links with javascript: URIs, since
  310. // they won't work after scripts have been removed from the page.
  311. if (href.indexOf("javascript:") === 0) {
  312. // if the link only contains simple text content, it can be converted to a text node
  313. if (link.childNodes.length === 1 && link.childNodes[0].nodeType === this.TEXT_NODE) {
  314. var text = this._doc.createTextNode(link.textContent);
  315. link.parentNode.replaceChild(text, link);
  316. } else {
  317. // if the link has multiple children, they should all be preserved
  318. var container = this._doc.createElement("span");
  319. while (link.childNodes.length > 0) {
  320. container.appendChild(link.childNodes[0]);
  321. }
  322. link.parentNode.replaceChild(container, link);
  323. }
  324. } else {
  325. link.setAttribute("href", toAbsoluteURI(href));
  326. }
  327. }
  328. });
  329. var imgs = this._getAllNodesWithTag(articleContent, ["img"]);
  330. this._forEachNode(imgs, function(img) {
  331. var src = img.getAttribute("src");
  332. if (src) {
  333. img.setAttribute("src", toAbsoluteURI(src));
  334. }
  335. });
  336. },
  337. /**
  338. * Get the article title as an H1.
  339. *
  340. * @return void
  341. **/
  342. _getArticleTitle: function() {
  343. var doc = this._doc;
  344. var curTitle = "";
  345. var origTitle = "";
  346. try {
  347. curTitle = origTitle = doc.title.trim();
  348. // If they had an element with id "title" in their HTML
  349. if (typeof curTitle !== "string")
  350. curTitle = origTitle = this._getInnerText(doc.getElementsByTagName("title")[0]);
  351. } catch (e) {/* ignore exceptions setting the title. */}
  352. var titleHadHierarchicalSeparators = false;
  353. function wordCount(str) {
  354. return str.split(/\s+/).length;
  355. }
  356. // If there's a separator in the title, first remove the final part
  357. if ((/ [\|\-\\\/>»] /).test(curTitle)) {
  358. titleHadHierarchicalSeparators = / [\\\/>»] /.test(curTitle);
  359. curTitle = origTitle.replace(/(.*)[\|\-\\\/>»] .*/gi, "$1");
  360. // If the resulting title is too short (3 words or fewer), remove
  361. // the first part instead:
  362. if (wordCount(curTitle) < 3)
  363. curTitle = origTitle.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi, "$1");
  364. } else if (curTitle.indexOf(": ") !== -1) {
  365. // Check if we have an heading containing this exact string, so we
  366. // could assume it's the full title.
  367. var headings = this._concatNodeLists(
  368. doc.getElementsByTagName("h1"),
  369. doc.getElementsByTagName("h2")
  370. );
  371. var trimmedTitle = curTitle.trim();
  372. var match = this._someNode(headings, function(heading) {
  373. return heading.textContent.trim() === trimmedTitle;
  374. });
  375. // If we don't, let's extract the title out of the original title string.
  376. if (!match) {
  377. curTitle = origTitle.substring(origTitle.lastIndexOf(":") + 1);
  378. // If the title is now too short, try the first colon instead:
  379. if (wordCount(curTitle) < 3) {
  380. curTitle = origTitle.substring(origTitle.indexOf(":") + 1);
  381. // But if we have too many words before the colon there's something weird
  382. // with the titles and the H tags so let's just use the original title instead
  383. } else if (wordCount(origTitle.substr(0, origTitle.indexOf(":"))) > 5) {
  384. curTitle = origTitle;
  385. }
  386. }
  387. } else if (curTitle.length > 150 || curTitle.length < 15) {
  388. var hOnes = doc.getElementsByTagName("h1");
  389. if (hOnes.length === 1)
  390. curTitle = this._getInnerText(hOnes[0]);
  391. }
  392. curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " ");
  393. // If we now have 4 words or fewer as our title, and either no
  394. // 'hierarchical' separators (\, /, > or ») were found in the original
  395. // title or we decreased the number of words by more than 1 word, use
  396. // the original title.
  397. var curTitleWordCount = wordCount(curTitle);
  398. if (curTitleWordCount <= 4 &&
  399. (!titleHadHierarchicalSeparators ||
  400. curTitleWordCount != wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1)) {
  401. curTitle = origTitle;
  402. }
  403. return curTitle;
  404. },
  405. /**
  406. * Prepare the HTML document for readability to scrape it.
  407. * This includes things like stripping javascript, CSS, and handling terrible markup.
  408. *
  409. * @return void
  410. **/
  411. _prepDocument: function() {
  412. var doc = this._doc;
  413. // Remove all style tags in head
  414. this._removeNodes(this._getAllNodesWithTag(doc, ["style"]));
  415. if (doc.body) {
  416. this._replaceBrs(doc.body);
  417. }
  418. this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN");
  419. },
  420. /**
  421. * Finds the next element, starting from the given node, and ignoring
  422. * whitespace in between. If the given node is an element, the same node is
  423. * returned.
  424. */
  425. _nextElement: function (node) {
  426. var next = node;
  427. while (next
  428. && (next.nodeType != this.ELEMENT_NODE)
  429. && this.REGEXPS.whitespace.test(next.textContent)) {
  430. next = next.nextSibling;
  431. }
  432. return next;
  433. },
  434. /**
  435. * Replaces 2 or more successive <br> elements with a single <p>.
  436. * Whitespace between <br> elements are ignored. For example:
  437. * <div>foo<br>bar<br> <br><br>abc</div>
  438. * will become:
  439. * <div>foo<br>bar<p>abc</p></div>
  440. */
  441. _replaceBrs: function (elem) {
  442. this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function(br) {
  443. var next = br.nextSibling;
  444. // Whether 2 or more <br> elements have been found and replaced with a
  445. // <p> block.
  446. var replaced = false;
  447. // If we find a <br> chain, remove the <br>s until we hit another element
  448. // or non-whitespace. This leaves behind the first <br> in the chain
  449. // (which will be replaced with a <p> later).
  450. while ((next = this._nextElement(next)) && (next.tagName == "BR")) {
  451. replaced = true;
  452. var brSibling = next.nextSibling;
  453. next.parentNode.removeChild(next);
  454. next = brSibling;
  455. }
  456. // If we removed a <br> chain, replace the remaining <br> with a <p>. Add
  457. // all sibling nodes as children of the <p> until we hit another <br>
  458. // chain.
  459. if (replaced) {
  460. var p = this._doc.createElement("p");
  461. br.parentNode.replaceChild(p, br);
  462. next = p.nextSibling;
  463. while (next) {
  464. // If we've hit another <br><br>, we're done adding children to this <p>.
  465. if (next.tagName == "BR") {
  466. var nextElem = this._nextElement(next.nextSibling);
  467. if (nextElem && nextElem.tagName == "BR")
  468. break;
  469. }
  470. if (!this._isPhrasingContent(next))
  471. break;
  472. // Otherwise, make this node a child of the new <p>.
  473. var sibling = next.nextSibling;
  474. p.appendChild(next);
  475. next = sibling;
  476. }
  477. while (p.lastChild && this._isWhitespace(p.lastChild)) {
  478. p.removeChild(p.lastChild);
  479. }
  480. if (p.parentNode.tagName === "P")
  481. this._setNodeTag(p.parentNode, "DIV");
  482. }
  483. });
  484. },
  485. _setNodeTag: function (node, tag) {
  486. this.log("_setNodeTag", node, tag);
  487. if (this._docJSDOMParser) {
  488. node.localName = tag.toLowerCase();
  489. node.tagName = tag.toUpperCase();
  490. return node;
  491. }
  492. var replacement = node.ownerDocument.createElement(tag);
  493. while (node.firstChild) {
  494. replacement.appendChild(node.firstChild);
  495. }
  496. node.parentNode.replaceChild(replacement, node);
  497. if (node.readability)
  498. replacement.readability = node.readability;
  499. for (var i = 0; i < node.attributes.length; i++) {
  500. try {
  501. replacement.setAttribute(node.attributes[i].name, node.attributes[i].value);
  502. } catch (ex) {
  503. /* it's possible for setAttribute() to throw if the attribute name
  504. * isn't a valid XML Name. Such attributes can however be parsed from
  505. * source in HTML docs, see https://github.com/whatwg/html/issues/4275,
  506. * so we can hit them here and then throw. We don't care about such
  507. * attributes so we ignore them.
  508. */
  509. }
  510. }
  511. return replacement;
  512. },
  513. /**
  514. * Prepare the article node for display. Clean out any inline styles,
  515. * iframes, forms, strip extraneous <p> tags, etc.
  516. *
  517. * @param Element
  518. * @return void
  519. **/
  520. _prepArticle: function(articleContent) {
  521. this._cleanStyles(articleContent);
  522. // Check for data tables before we continue, to avoid removing items in
  523. // those tables, which will often be isolated even though they're
  524. // visually linked to other content-ful elements (text, images, etc.).
  525. this._markDataTables(articleContent);
  526. this._fixLazyImages(articleContent);
  527. // Clean out junk from the article content
  528. this._cleanConditionally(articleContent, "form");
  529. this._cleanConditionally(articleContent, "fieldset");
  530. this._clean(articleContent, "object");
  531. this._clean(articleContent, "embed");
  532. this._clean(articleContent, "h1");
  533. this._clean(articleContent, "footer");
  534. this._clean(articleContent, "link");
  535. this._clean(articleContent, "aside");
  536. // Clean out elements with little content that have "share" in their id/class combinations from final top candidates,
  537. // which means we don't remove the top candidates even they have "share".
  538. var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD;
  539. this._forEachNode(articleContent.children, function (topCandidate) {
  540. this._cleanMatchedNodes(topCandidate, function (node, matchString) {
  541. return this.REGEXPS.shareElements.test(matchString) && node.textContent.length < shareElementThreshold;
  542. });
  543. });
  544. // If there is only one h2 and its text content substantially equals article title,
  545. // they are probably using it as a header and not a subheader,
  546. // so remove it since we already extract the title separately.
  547. var h2 = articleContent.getElementsByTagName("h2");
  548. if (h2.length === 1) {
  549. var lengthSimilarRate = (h2[0].textContent.length - this._articleTitle.length) / this._articleTitle.length;
  550. if (Math.abs(lengthSimilarRate) < 0.5) {
  551. var titlesMatch = false;
  552. if (lengthSimilarRate > 0) {
  553. titlesMatch = h2[0].textContent.includes(this._articleTitle);
  554. } else {
  555. titlesMatch = this._articleTitle.includes(h2[0].textContent);
  556. }
  557. if (titlesMatch) {
  558. this._clean(articleContent, "h2");
  559. }
  560. }
  561. }
  562. this._clean(articleContent, "iframe");
  563. this._clean(articleContent, "input");
  564. this._clean(articleContent, "textarea");
  565. this._clean(articleContent, "select");
  566. this._clean(articleContent, "button");
  567. this._cleanHeaders(articleContent);
  568. // Do these last as the previous stuff may have removed junk
  569. // that will affect these
  570. this._cleanConditionally(articleContent, "table");
  571. this._cleanConditionally(articleContent, "ul");
  572. this._cleanConditionally(articleContent, "div");
  573. // Remove extra paragraphs
  574. this._removeNodes(this._getAllNodesWithTag(articleContent, ["p"]), function (paragraph) {
  575. var imgCount = paragraph.getElementsByTagName("img").length;
  576. var embedCount = paragraph.getElementsByTagName("embed").length;
  577. var objectCount = paragraph.getElementsByTagName("object").length;
  578. // At this point, nasty iframes have been removed, only remain embedded video ones.
  579. var iframeCount = paragraph.getElementsByTagName("iframe").length;
  580. var totalCount = imgCount + embedCount + objectCount + iframeCount;
  581. return totalCount === 0 && !this._getInnerText(paragraph, false);
  582. });
  583. this._forEachNode(this._getAllNodesWithTag(articleContent, ["br"]), function(br) {
  584. var next = this._nextElement(br.nextSibling);
  585. if (next && next.tagName == "P")
  586. br.parentNode.removeChild(br);
  587. });
  588. // Remove single-cell tables
  589. this._forEachNode(this._getAllNodesWithTag(articleContent, ["table"]), function(table) {
  590. var tbody = this._hasSingleTagInsideElement(table, "TBODY") ? table.firstElementChild : table;
  591. if (this._hasSingleTagInsideElement(tbody, "TR")) {
  592. var row = tbody.firstElementChild;
  593. if (this._hasSingleTagInsideElement(row, "TD")) {
  594. var cell = row.firstElementChild;
  595. cell = this._setNodeTag(cell, this._everyNode(cell.childNodes, this._isPhrasingContent) ? "P" : "DIV");
  596. table.parentNode.replaceChild(cell, table);
  597. }
  598. }
  599. });
  600. },
  601. /**
  602. * Initialize a node with the readability object. Also checks the
  603. * className/id for special names to add to its score.
  604. *
  605. * @param Element
  606. * @return void
  607. **/
  608. _initializeNode: function(node) {
  609. node.readability = {"contentScore": 0};
  610. switch (node.tagName) {
  611. case "DIV":
  612. node.readability.contentScore += 5;
  613. break;
  614. case "PRE":
  615. case "TD":
  616. case "BLOCKQUOTE":
  617. node.readability.contentScore += 3;
  618. break;
  619. case "ADDRESS":
  620. case "OL":
  621. case "UL":
  622. case "DL":
  623. case "DD":
  624. case "DT":
  625. case "LI":
  626. case "FORM":
  627. node.readability.contentScore -= 3;
  628. break;
  629. case "H1":
  630. case "H2":
  631. case "H3":
  632. case "H4":
  633. case "H5":
  634. case "H6":
  635. case "TH":
  636. node.readability.contentScore -= 5;
  637. break;
  638. }
  639. node.readability.contentScore += this._getClassWeight(node);
  640. },
  641. _removeAndGetNext: function(node) {
  642. var nextNode = this._getNextNode(node, true);
  643. node.parentNode.removeChild(node);
  644. return nextNode;
  645. },
  646. /**
  647. * Traverse the DOM from node to node, starting at the node passed in.
  648. * Pass true for the second parameter to indicate this node itself
  649. * (and its kids) are going away, and we want the next node over.
  650. *
  651. * Calling this in a loop will traverse the DOM depth-first.
  652. */
  653. _getNextNode: function(node, ignoreSelfAndKids) {
  654. // First check for kids if those aren't being ignored
  655. if (!ignoreSelfAndKids && node.firstElementChild) {
  656. return node.firstElementChild;
  657. }
  658. // Then for siblings...
  659. if (node.nextElementSibling) {
  660. return node.nextElementSibling;
  661. }
  662. // And finally, move up the parent chain *and* find a sibling
  663. // (because this is depth-first traversal, we will have already
  664. // seen the parent nodes themselves).
  665. do {
  666. node = node.parentNode;
  667. } while (node && !node.nextElementSibling);
  668. return node && node.nextElementSibling;
  669. },
  670. _checkByline: function(node, matchString) {
  671. if (this._articleByline) {
  672. return false;
  673. }
  674. if (node.getAttribute !== undefined) {
  675. var rel = node.getAttribute("rel");
  676. var itemprop = node.getAttribute("itemprop");
  677. }
  678. if ((rel === "author" || (itemprop && itemprop.indexOf("author") !== -1) || this.REGEXPS.byline.test(matchString)) && this._isValidByline(node.textContent)) {
  679. this._articleByline = node.textContent.trim();
  680. return true;
  681. }
  682. return false;
  683. },
  684. _getNodeAncestors: function(node, maxDepth) {
  685. maxDepth = maxDepth || 0;
  686. var i = 0, ancestors = [];
  687. while (node.parentNode) {
  688. ancestors.push(node.parentNode);
  689. if (maxDepth && ++i === maxDepth)
  690. break;
  691. node = node.parentNode;
  692. }
  693. return ancestors;
  694. },
  695. /***
  696. * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
  697. * most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
  698. *
  699. * @param page a document to run upon. Needs to be a full document, complete with body.
  700. * @return Element
  701. **/
  702. _grabArticle: function (page) {
  703. this.log("**** grabArticle ****");
  704. var doc = this._doc;
  705. var isPaging = (page !== null ? true: false);
  706. page = page ? page : this._doc.body;
  707. // We can't grab an article if we don't have a page!
  708. if (!page) {
  709. this.log("No body found in document. Abort.");
  710. return null;
  711. }
  712. var pageCacheHtml = page.innerHTML;
  713. while (true) {
  714. var stripUnlikelyCandidates = this._flagIsActive(this.FLAG_STRIP_UNLIKELYS);
  715. // First, node prepping. Trash nodes that look cruddy (like ones with the
  716. // class name "comment", etc), and turn divs into P tags where they have been
  717. // used inappropriately (as in, where they contain no other block level elements.)
  718. var elementsToScore = [];
  719. var node = this._doc.documentElement;
  720. while (node) {
  721. var matchString = node.className + " " + node.id;
  722. if (!this._isProbablyVisible(node)) {
  723. this.log("Removing hidden node - " + matchString);
  724. node = this._removeAndGetNext(node);
  725. continue;
  726. }
  727. // Check to see if this node is a byline, and remove it if it is.
  728. if (this._checkByline(node, matchString)) {
  729. node = this._removeAndGetNext(node);
  730. continue;
  731. }
  732. // Remove unlikely candidates
  733. if (stripUnlikelyCandidates) {
  734. if (this.REGEXPS.unlikelyCandidates.test(matchString) &&
  735. !this.REGEXPS.okMaybeItsACandidate.test(matchString) &&
  736. !this._hasAncestorTag(node, "table") &&
  737. node.tagName !== "BODY" &&
  738. node.tagName !== "A") {
  739. this.log("Removing unlikely candidate - " + matchString);
  740. node = this._removeAndGetNext(node);
  741. continue;
  742. }
  743. if (node.getAttribute("role") == "complementary") {
  744. this.log("Removing complementary content - " + matchString);
  745. node = this._removeAndGetNext(node);
  746. continue;
  747. }
  748. }
  749. // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
  750. if ((node.tagName === "DIV" || node.tagName === "SECTION" || node.tagName === "HEADER" ||
  751. node.tagName === "H1" || node.tagName === "H2" || node.tagName === "H3" ||
  752. node.tagName === "H4" || node.tagName === "H5" || node.tagName === "H6") &&
  753. this._isElementWithoutContent(node)) {
  754. node = this._removeAndGetNext(node);
  755. continue;
  756. }
  757. if (this.DEFAULT_TAGS_TO_SCORE.indexOf(node.tagName) !== -1) {
  758. elementsToScore.push(node);
  759. }
  760. // Turn all divs that don't have children block level elements into p's
  761. if (node.tagName === "DIV") {
  762. // Put phrasing content into paragraphs.
  763. var p = null;
  764. var childNode = node.firstChild;
  765. while (childNode) {
  766. var nextSibling = childNode.nextSibling;
  767. if (this._isPhrasingContent(childNode)) {
  768. if (p !== null) {
  769. p.appendChild(childNode);
  770. } else if (!this._isWhitespace(childNode)) {
  771. p = doc.createElement("p");
  772. node.replaceChild(p, childNode);
  773. p.appendChild(childNode);
  774. }
  775. } else if (p !== null) {
  776. while (p.lastChild && this._isWhitespace(p.lastChild)) {
  777. p.removeChild(p.lastChild);
  778. }
  779. p = null;
  780. }
  781. childNode = nextSibling;
  782. }
  783. // Sites like http://mobile.slate.com encloses each paragraph with a DIV
  784. // element. DIVs with only a P element inside and no text content can be
  785. // safely converted into plain P elements to avoid confusing the scoring
  786. // algorithm with DIVs with are, in practice, paragraphs.
  787. if (this._hasSingleTagInsideElement(node, "P") && this._getLinkDensity(node) < 0.25) {
  788. var newNode = node.children[0];
  789. node.parentNode.replaceChild(newNode, node);
  790. node = newNode;
  791. elementsToScore.push(node);
  792. } else if (!this._hasChildBlockElement(node)) {
  793. node = this._setNodeTag(node, "P");
  794. elementsToScore.push(node);
  795. }
  796. }
  797. node = this._getNextNode(node);
  798. }
  799. /**
  800. * Loop through all paragraphs, and assign a score to them based on how content-y they look.
  801. * Then add their score to their parent node.
  802. *
  803. * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
  804. **/
  805. var candidates = [];
  806. this._forEachNode(elementsToScore, function(elementToScore) {
  807. if (!elementToScore.parentNode || typeof(elementToScore.parentNode.tagName) === "undefined")
  808. return;
  809. // If this paragraph is less than 25 characters, don't even count it.
  810. var innerText = this._getInnerText(elementToScore);
  811. if (innerText.length < 25)
  812. return;
  813. // Exclude nodes with no ancestor.
  814. var ancestors = this._getNodeAncestors(elementToScore, 3);
  815. if (ancestors.length === 0)
  816. return;
  817. var contentScore = 0;
  818. // Add a point for the paragraph itself as a base.
  819. contentScore += 1;
  820. // Add points for any commas within this paragraph.
  821. contentScore += innerText.split(",").length;
  822. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  823. contentScore += Math.min(Math.floor(innerText.length / 100), 3);
  824. // Initialize and score ancestors.
  825. this._forEachNode(ancestors, function(ancestor, level) {
  826. if (!ancestor.tagName || !ancestor.parentNode || typeof(ancestor.parentNode.tagName) === "undefined")
  827. return;
  828. if (typeof(ancestor.readability) === "undefined") {
  829. this._initializeNode(ancestor);
  830. candidates.push(ancestor);
  831. }
  832. // Node score divider:
  833. // - parent: 1 (no division)
  834. // - grandparent: 2
  835. // - great grandparent+: ancestor level * 3
  836. if (level === 0)
  837. var scoreDivider = 1;
  838. else if (level === 1)
  839. scoreDivider = 2;
  840. else
  841. scoreDivider = level * 3;
  842. ancestor.readability.contentScore += contentScore / scoreDivider;
  843. });
  844. });
  845. // After we've calculated scores, loop through all of the possible
  846. // candidate nodes we found and find the one with the highest score.
  847. var topCandidates = [];
  848. for (var c = 0, cl = candidates.length; c < cl; c += 1) {
  849. var candidate = candidates[c];
  850. // Scale the final candidates score based on link density. Good content
  851. // should have a relatively small link density (5% or less) and be mostly
  852. // unaffected by this operation.
  853. var candidateScore = candidate.readability.contentScore * (1 - this._getLinkDensity(candidate));
  854. candidate.readability.contentScore = candidateScore;
  855. this.log("Candidate:", candidate, "with score " + candidateScore);
  856. for (var t = 0; t < this._nbTopCandidates; t++) {
  857. var aTopCandidate = topCandidates[t];
  858. if (!aTopCandidate || candidateScore > aTopCandidate.readability.contentScore) {
  859. topCandidates.splice(t, 0, candidate);
  860. if (topCandidates.length > this._nbTopCandidates)
  861. topCandidates.pop();
  862. break;
  863. }
  864. }
  865. }
  866. var topCandidate = topCandidates[0] || null;
  867. var neededToCreateTopCandidate = false;
  868. var parentOfTopCandidate;
  869. // If we still have no top candidate, just use the body as a last resort.
  870. // We also have to copy the body node so it is something we can modify.
  871. if (topCandidate === null || topCandidate.tagName === "BODY") {
  872. // Move all of the page's children into topCandidate
  873. topCandidate = doc.createElement("DIV");
  874. neededToCreateTopCandidate = true;
  875. // Move everything (not just elements, also text nodes etc.) into the container
  876. // so we even include text directly in the body:
  877. var kids = page.childNodes;
  878. while (kids.length) {
  879. this.log("Moving child out:", kids[0]);
  880. topCandidate.appendChild(kids[0]);
  881. }
  882. page.appendChild(topCandidate);
  883. this._initializeNode(topCandidate);
  884. } else if (topCandidate) {
  885. // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
  886. // and whose scores are quite closed with current `topCandidate` node.
  887. var alternativeCandidateAncestors = [];
  888. for (var i = 1; i < topCandidates.length; i++) {
  889. if (topCandidates[i].readability.contentScore / topCandidate.readability.contentScore >= 0.75) {
  890. alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i]));
  891. }
  892. }
  893. var MINIMUM_TOPCANDIDATES = 3;
  894. if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) {
  895. parentOfTopCandidate = topCandidate.parentNode;
  896. while (parentOfTopCandidate.tagName !== "BODY") {
  897. var listsContainingThisAncestor = 0;
  898. for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) {
  899. listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate));
  900. }
  901. if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) {
  902. topCandidate = parentOfTopCandidate;
  903. break;
  904. }
  905. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  906. }
  907. }
  908. if (!topCandidate.readability) {
  909. this._initializeNode(topCandidate);
  910. }
  911. // Because of our bonus system, parents of candidates might have scores
  912. // themselves. They get half of the node. There won't be nodes with higher
  913. // scores than our topCandidate, but if we see the score going *up* in the first
  914. // few steps up the tree, that's a decent sign that there might be more content
  915. // lurking in other places that we want to unify in. The sibling stuff
  916. // below does some of that - but only if we've looked high enough up the DOM
  917. // tree.
  918. parentOfTopCandidate = topCandidate.parentNode;
  919. var lastScore = topCandidate.readability.contentScore;
  920. // The scores shouldn't get too low.
  921. var scoreThreshold = lastScore / 3;
  922. while (parentOfTopCandidate.tagName !== "BODY") {
  923. if (!parentOfTopCandidate.readability) {
  924. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  925. continue;
  926. }
  927. var parentScore = parentOfTopCandidate.readability.contentScore;
  928. if (parentScore < scoreThreshold)
  929. break;
  930. if (parentScore > lastScore) {
  931. // Alright! We found a better parent to use.
  932. topCandidate = parentOfTopCandidate;
  933. break;
  934. }
  935. lastScore = parentOfTopCandidate.readability.contentScore;
  936. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  937. }
  938. // If the top candidate is the only child, use parent instead. This will help sibling
  939. // joining logic when adjacent content is actually located in parent's sibling node.
  940. parentOfTopCandidate = topCandidate.parentNode;
  941. while (parentOfTopCandidate.tagName != "BODY" && parentOfTopCandidate.children.length == 1) {
  942. topCandidate = parentOfTopCandidate;
  943. parentOfTopCandidate = topCandidate.parentNode;
  944. }
  945. if (!topCandidate.readability) {
  946. this._initializeNode(topCandidate);
  947. }
  948. }
  949. // Now that we have the top candidate, look through its siblings for content
  950. // that might also be related. Things like preambles, content split by ads
  951. // that we removed, etc.
  952. var articleContent = doc.createElement("DIV");
  953. if (isPaging)
  954. articleContent.id = "readability-content";
  955. var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2);
  956. // Keep potential top candidate's parent node to try to get text direction of it later.
  957. parentOfTopCandidate = topCandidate.parentNode;
  958. var siblings = parentOfTopCandidate.children;
  959. for (var s = 0, sl = siblings.length; s < sl; s++) {
  960. var sibling = siblings[s];
  961. var append = false;
  962. this.log("Looking at sibling node:", sibling, sibling.readability ? ("with score " + sibling.readability.contentScore) : "");
  963. this.log("Sibling has score", sibling.readability ? sibling.readability.contentScore : "Unknown");
  964. if (sibling === topCandidate) {
  965. append = true;
  966. } else {
  967. var contentBonus = 0;
  968. // Give a bonus if sibling nodes and top candidates have the example same classname
  969. if (sibling.className === topCandidate.className && topCandidate.className !== "")
  970. contentBonus += topCandidate.readability.contentScore * 0.2;
  971. if (sibling.readability &&
  972. ((sibling.readability.contentScore + contentBonus) >= siblingScoreThreshold)) {
  973. append = true;
  974. } else if (sibling.nodeName === "P") {
  975. var linkDensity = this._getLinkDensity(sibling);
  976. var nodeContent = this._getInnerText(sibling);
  977. var nodeLength = nodeContent.length;
  978. if (nodeLength > 80 && linkDensity < 0.25) {
  979. append = true;
  980. } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 &&
  981. nodeContent.search(/\.( |$)/) !== -1) {
  982. append = true;
  983. }
  984. }
  985. }
  986. if (append) {
  987. this.log("Appending node:", sibling);
  988. if (this.ALTER_TO_DIV_EXCEPTIONS.indexOf(sibling.nodeName) === -1) {
  989. // We have a node that isn't a common block level element, like a form or td tag.
  990. // Turn it into a div so it doesn't get filtered out later by accident.
  991. this.log("Altering sibling:", sibling, "to div.");
  992. sibling = this._setNodeTag(sibling, "DIV");
  993. }
  994. articleContent.appendChild(sibling);
  995. // siblings is a reference to the children array, and
  996. // sibling is removed from the array when we call appendChild().
  997. // As a result, we must revisit this index since the nodes
  998. // have been shifted.
  999. s -= 1;
  1000. sl -= 1;
  1001. }
  1002. }
  1003. if (this._debug)
  1004. this.log("Article content pre-prep: " + articleContent.innerHTML);
  1005. // So we have all of the content that we need. Now we clean it up for presentation.
  1006. this._prepArticle(articleContent);
  1007. if (this._debug)
  1008. this.log("Article content post-prep: " + articleContent.innerHTML);
  1009. if (neededToCreateTopCandidate) {
  1010. // We already created a fake div thing, and there wouldn't have been any siblings left
  1011. // for the previous loop, so there's no point trying to create a new div, and then
  1012. // move all the children over. Just assign IDs and class names here. No need to append
  1013. // because that already happened anyway.
  1014. topCandidate.id = "readability-page-1";
  1015. topCandidate.className = "page";
  1016. } else {
  1017. var div = doc.createElement("DIV");
  1018. div.id = "readability-page-1";
  1019. div.className = "page";
  1020. var children = articleContent.childNodes;
  1021. while (children.length) {
  1022. div.appendChild(children[0]);
  1023. }
  1024. articleContent.appendChild(div);
  1025. }
  1026. if (this._debug)
  1027. this.log("Article content after paging: " + articleContent.innerHTML);
  1028. var parseSuccessful = true;
  1029. // Now that we've gone through the full algorithm, check to see if
  1030. // we got any meaningful content. If we didn't, we may need to re-run
  1031. // grabArticle with different flags set. This gives us a higher likelihood of
  1032. // finding the content, and the sieve approach gives us a higher likelihood of
  1033. // finding the -right- content.
  1034. var textLength = this._getInnerText(articleContent, true).length;
  1035. if (textLength < this._charThreshold) {
  1036. parseSuccessful = false;
  1037. page.innerHTML = pageCacheHtml;
  1038. if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) {
  1039. this._removeFlag(this.FLAG_STRIP_UNLIKELYS);
  1040. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1041. } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
  1042. this._removeFlag(this.FLAG_WEIGHT_CLASSES);
  1043. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1044. } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
  1045. this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);
  1046. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1047. } else {
  1048. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1049. // No luck after removing flags, just return the longest text we found during the different loops
  1050. this._attempts.sort(function (a, b) {
  1051. return b.textLength - a.textLength;
  1052. });
  1053. // But first check if we actually have something
  1054. if (!this._attempts[0].textLength) {
  1055. return null;
  1056. }
  1057. articleContent = this._attempts[0].articleContent;
  1058. parseSuccessful = true;
  1059. }
  1060. }
  1061. if (parseSuccessful) {
  1062. // Find out text direction from ancestors of final top candidate.
  1063. var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate));
  1064. this._someNode(ancestors, function(ancestor) {
  1065. if (!ancestor.tagName)
  1066. return false;
  1067. var articleDir = ancestor.getAttribute("dir");
  1068. if (articleDir) {
  1069. this._articleDir = articleDir;
  1070. return true;
  1071. }
  1072. return false;
  1073. });
  1074. return articleContent;
  1075. }
  1076. }
  1077. },
  1078. /**
  1079. * Check whether the input string could be a byline.
  1080. * This verifies that the input is a string, and that the length
  1081. * is less than 100 chars.
  1082. *
  1083. * @param possibleByline {string} - a string to check whether its a byline.
  1084. * @return Boolean - whether the input string is a byline.
  1085. */
  1086. _isValidByline: function(byline) {
  1087. if (typeof byline == "string" || byline instanceof String) {
  1088. byline = byline.trim();
  1089. return (byline.length > 0) && (byline.length < 100);
  1090. }
  1091. return false;
  1092. },
  1093. /**
  1094. * Attempts to get excerpt and byline metadata for the article.
  1095. *
  1096. * @return Object with optional "excerpt" and "byline" properties
  1097. */
  1098. _getArticleMetadata: function() {
  1099. var metadata = {};
  1100. var values = {};
  1101. var metaElements = this._doc.getElementsByTagName("meta");
  1102. // property is a space-separated list of values
  1103. var propertyPattern = /\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|site_name)\s*/gi;
  1104. // name is a single value
  1105. var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;
  1106. // Find description tags.
  1107. this._forEachNode(metaElements, function(element) {
  1108. var elementName = element.getAttribute("name");
  1109. var elementProperty = element.getAttribute("property");
  1110. var content = element.getAttribute("content");
  1111. if (!content) {
  1112. return;
  1113. }
  1114. var matches = null;
  1115. var name = null;
  1116. if (elementProperty) {
  1117. matches = elementProperty.match(propertyPattern);
  1118. if (matches) {
  1119. for (var i = matches.length - 1; i >= 0; i--) {
  1120. // Convert to lowercase, and remove any whitespace
  1121. // so we can match below.
  1122. name = matches[i].toLowerCase().replace(/\s/g, "");
  1123. // multiple authors
  1124. values[name] = content.trim();
  1125. }
  1126. }
  1127. }
  1128. if (!matches && elementName && namePattern.test(elementName)) {
  1129. name = elementName;
  1130. if (content) {
  1131. // Convert to lowercase, remove any whitespace, and convert dots
  1132. // to colons so we can match below.
  1133. name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":");
  1134. values[name] = content.trim();
  1135. }
  1136. }
  1137. });
  1138. // get title
  1139. metadata.title = values["dc:title"] ||
  1140. values["dcterm:title"] ||
  1141. values["og:title"] ||
  1142. values["weibo:article:title"] ||
  1143. values["weibo:webpage:title"] ||
  1144. values["title"] ||
  1145. values["twitter:title"];
  1146. if (!metadata.title) {
  1147. metadata.title = this._getArticleTitle();
  1148. }
  1149. // get author
  1150. metadata.byline = values["dc:creator"] ||
  1151. values["dcterm:creator"] ||
  1152. values["author"];
  1153. // get description
  1154. metadata.excerpt = values["dc:description"] ||
  1155. values["dcterm:description"] ||
  1156. values["og:description"] ||
  1157. values["weibo:article:description"] ||
  1158. values["weibo:webpage:description"] ||
  1159. values["description"] ||
  1160. values["twitter:description"];
  1161. // get site name
  1162. metadata.siteName = values["og:site_name"];
  1163. return metadata;
  1164. },
  1165. /**
  1166. * Check if node is image, or if node contains exactly only one image
  1167. * whether as a direct child or as its descendants.
  1168. *
  1169. * @param Element
  1170. **/
  1171. _isSingleImage: function(node) {
  1172. if (node.tagName === "IMG") {
  1173. return true;
  1174. }
  1175. if (node.children.length !== 1 || node.textContent.trim() !== "") {
  1176. return false;
  1177. }
  1178. return this._isSingleImage(node.children[0]);
  1179. },
  1180. /**
  1181. * Find all <noscript> that are located after <img> nodes, and which contain only one
  1182. * <img> element. Replace the first image with the image from inside the <noscript> tag,
  1183. * and remove the <noscript> tag. This improves the quality of the images we use on
  1184. * some sites (e.g. Medium).
  1185. *
  1186. * @param Element
  1187. **/
  1188. _unwrapNoscriptImages: function(doc) {
  1189. // Find img without source or attributes that might contains image, and remove it.
  1190. // This is done to prevent a placeholder img is replaced by img from noscript in next step.
  1191. var imgs = Array.from(doc.getElementsByTagName("img"));
  1192. this._forEachNode(imgs, function(img) {
  1193. for (var i = 0; i < img.attributes.length; i++) {
  1194. var attr = img.attributes[i];
  1195. switch (attr.name) {
  1196. case "src":
  1197. case "srcset":
  1198. case "data-src":
  1199. case "data-srcset":
  1200. return;
  1201. }
  1202. if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1203. return;
  1204. }
  1205. }
  1206. img.parentNode.removeChild(img);
  1207. });
  1208. // Next find noscript and try to extract its image
  1209. var noscripts = Array.from(doc.getElementsByTagName("noscript"));
  1210. this._forEachNode(noscripts, function(noscript) {
  1211. // Parse content of noscript and make sure it only contains image
  1212. var tmp = doc.createElement("div");
  1213. tmp.innerHTML = noscript.innerHTML;
  1214. if (!this._isSingleImage(tmp)) {
  1215. return;
  1216. }
  1217. // If noscript has previous sibling and it only contains image,
  1218. // replace it with noscript content. However we also keep old
  1219. // attributes that might contains image.
  1220. var prevElement = noscript.previousElementSibling;
  1221. if (prevElement && this._isSingleImage(prevElement)) {
  1222. var prevImg = prevElement;
  1223. if (prevImg.tagName !== "IMG") {
  1224. prevImg = prevElement.getElementsByTagName("img")[0];
  1225. }
  1226. var newImg = tmp.getElementsByTagName("img")[0];
  1227. for (var i = 0; i < prevImg.attributes.length; i++) {
  1228. var attr = prevImg.attributes[i];
  1229. if (attr.value === "") {
  1230. continue;
  1231. }
  1232. if (attr.name === "src" || attr.name === "srcset" || /\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1233. if (newImg.getAttribute(attr.name) === attr.value) {
  1234. continue;
  1235. }
  1236. var attrName = attr.name;
  1237. if (newImg.hasAttribute(attrName)) {
  1238. attrName = "data-old-" + attrName;
  1239. }
  1240. newImg.setAttribute(attrName, attr.value);
  1241. }
  1242. }
  1243. noscript.parentNode.replaceChild(tmp.firstElementChild, prevElement);
  1244. }
  1245. });
  1246. },
  1247. /**
  1248. * Removes script tags from the document.
  1249. *
  1250. * @param Element
  1251. **/
  1252. _removeScripts: function(doc) {
  1253. this._removeNodes(this._getAllNodesWithTag(doc, ["script"]), function(scriptNode) {
  1254. scriptNode.nodeValue = "";
  1255. scriptNode.removeAttribute("src");
  1256. return true;
  1257. });
  1258. this._removeNodes(this._getAllNodesWithTag(doc, ["noscript"]));
  1259. },
  1260. /**
  1261. * Check if this node has only whitespace and a single element with given tag
  1262. * Returns false if the DIV node contains non-empty text nodes
  1263. * or if it contains no element with given tag or more than 1 element.
  1264. *
  1265. * @param Element
  1266. * @param string tag of child element
  1267. **/
  1268. _hasSingleTagInsideElement: function(element, tag) {
  1269. // There should be exactly 1 element child with given tag
  1270. if (element.children.length != 1 || element.children[0].tagName !== tag) {
  1271. return false;
  1272. }
  1273. // And there should be no text nodes with real content
  1274. return !this._someNode(element.childNodes, function(node) {
  1275. return node.nodeType === this.TEXT_NODE &&
  1276. this.REGEXPS.hasContent.test(node.textContent);
  1277. });
  1278. },
  1279. _isElementWithoutContent: function(node) {
  1280. return node.nodeType === this.ELEMENT_NODE &&
  1281. node.textContent.trim().length == 0 &&
  1282. (node.children.length == 0 ||
  1283. node.children.length == node.getElementsByTagName("br").length + node.getElementsByTagName("hr").length);
  1284. },
  1285. /**
  1286. * Determine whether element has any children block level elements.
  1287. *
  1288. * @param Element
  1289. */
  1290. _hasChildBlockElement: function (element) {
  1291. return this._someNode(element.childNodes, function(node) {
  1292. return this.DIV_TO_P_ELEMS.indexOf(node.tagName) !== -1 ||
  1293. this._hasChildBlockElement(node);
  1294. });
  1295. },
  1296. /***
  1297. * Determine if a node qualifies as phrasing content.
  1298. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
  1299. **/
  1300. _isPhrasingContent: function(node) {
  1301. return node.nodeType === this.TEXT_NODE || this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 ||
  1302. ((node.tagName === "A" || node.tagName === "DEL" || node.tagName === "INS") &&
  1303. this._everyNode(node.childNodes, this._isPhrasingContent));
  1304. },
  1305. _isWhitespace: function(node) {
  1306. return (node.nodeType === this.TEXT_NODE && node.textContent.trim().length === 0) ||
  1307. (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR");
  1308. },
  1309. /**
  1310. * Get the inner text of a node - cross browser compatibly.
  1311. * This also strips out any excess whitespace to be found.
  1312. *
  1313. * @param Element
  1314. * @param Boolean normalizeSpaces (default: true)
  1315. * @return string
  1316. **/
  1317. _getInnerText: function(e, normalizeSpaces) {
  1318. normalizeSpaces = (typeof normalizeSpaces === "undefined") ? true : normalizeSpaces;
  1319. var textContent = e.textContent.trim();
  1320. if (normalizeSpaces) {
  1321. return textContent.replace(this.REGEXPS.normalize, " ");
  1322. }
  1323. return textContent;
  1324. },
  1325. /**
  1326. * Get the number of times a string s appears in the node e.
  1327. *
  1328. * @param Element
  1329. * @param string - what to split on. Default is ","
  1330. * @return number (integer)
  1331. **/
  1332. _getCharCount: function(e, s) {
  1333. s = s || ",";
  1334. return this._getInnerText(e).split(s).length - 1;
  1335. },
  1336. /**
  1337. * Remove the style attribute on every e and under.
  1338. * TODO: Test if getElementsByTagName(*) is faster.
  1339. *
  1340. * @param Element
  1341. * @return void
  1342. **/
  1343. _cleanStyles: function(e) {
  1344. if (!e || e.tagName.toLowerCase() === "svg")
  1345. return;
  1346. // Remove `style` and deprecated presentational attributes
  1347. for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) {
  1348. e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);
  1349. }
  1350. if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.indexOf(e.tagName) !== -1) {
  1351. e.removeAttribute("width");
  1352. e.removeAttribute("height");
  1353. }
  1354. var cur = e.firstElementChild;
  1355. while (cur !== null) {
  1356. this._cleanStyles(cur);
  1357. cur = cur.nextElementSibling;
  1358. }
  1359. },
  1360. /**
  1361. * Get the density of links as a percentage of the content
  1362. * This is the amount of text that is inside a link divided by the total text in the node.
  1363. *
  1364. * @param Element
  1365. * @return number (float)
  1366. **/
  1367. _getLinkDensity: function(element) {
  1368. var textLength = this._getInnerText(element).length;
  1369. if (textLength === 0)
  1370. return 0;
  1371. var linkLength = 0;
  1372. // XXX implement _reduceNodeList?
  1373. this._forEachNode(element.getElementsByTagName("a"), function(linkNode) {
  1374. linkLength += this._getInnerText(linkNode).length;
  1375. });
  1376. return linkLength / textLength;
  1377. },
  1378. /**
  1379. * Get an elements class/id weight. Uses regular expressions to tell if this
  1380. * element looks good or bad.
  1381. *
  1382. * @param Element
  1383. * @return number (Integer)
  1384. **/
  1385. _getClassWeight: function(e) {
  1386. if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES))
  1387. return 0;
  1388. var weight = 0;
  1389. // Look for a special classname
  1390. if (typeof(e.className) === "string" && e.className !== "") {
  1391. if (this.REGEXPS.negative.test(e.className))
  1392. weight -= 25;
  1393. if (this.REGEXPS.positive.test(e.className))
  1394. weight += 25;
  1395. }
  1396. // Look for a special ID
  1397. if (typeof(e.id) === "string" && e.id !== "") {
  1398. if (this.REGEXPS.negative.test(e.id))
  1399. weight -= 25;
  1400. if (this.REGEXPS.positive.test(e.id))
  1401. weight += 25;
  1402. }
  1403. return weight;
  1404. },
  1405. /**
  1406. * Clean a node of all elements of type "tag".
  1407. * (Unless it's a youtube/vimeo video. People love movies.)
  1408. *
  1409. * @param Element
  1410. * @param string tag to clean
  1411. * @return void
  1412. **/
  1413. _clean: function(e, tag) {
  1414. var isEmbed = ["object", "embed", "iframe"].indexOf(tag) !== -1;
  1415. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(element) {
  1416. // Allow youtube and vimeo videos through as people usually want to see those.
  1417. if (isEmbed) {
  1418. // First, check the elements attributes to see if any of them contain youtube or vimeo
  1419. for (var i = 0; i < element.attributes.length; i++) {
  1420. if (this.REGEXPS.videos.test(element.attributes[i].value)) {
  1421. return false;
  1422. }
  1423. }
  1424. // For embed with <object> tag, check inner HTML as well.
  1425. if (element.tagName === "object" && this.REGEXPS.videos.test(element.innerHTML)) {
  1426. return false;
  1427. }
  1428. }
  1429. return true;
  1430. });
  1431. },
  1432. /**
  1433. * Check if a given node has one of its ancestor tag name matching the
  1434. * provided one.
  1435. * @param HTMLElement node
  1436. * @param String tagName
  1437. * @param Number maxDepth
  1438. * @param Function filterFn a filter to invoke to determine whether this node 'counts'
  1439. * @return Boolean
  1440. */
  1441. _hasAncestorTag: function(node, tagName, maxDepth, filterFn) {
  1442. maxDepth = maxDepth || 3;
  1443. tagName = tagName.toUpperCase();
  1444. var depth = 0;
  1445. while (node.parentNode) {
  1446. if (maxDepth > 0 && depth > maxDepth)
  1447. return false;
  1448. if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode)))
  1449. return true;
  1450. node = node.parentNode;
  1451. depth++;
  1452. }
  1453. return false;
  1454. },
  1455. /**
  1456. * Return an object indicating how many rows and columns this table has.
  1457. */
  1458. _getRowAndColumnCount: function(table) {
  1459. var rows = 0;
  1460. var columns = 0;
  1461. var trs = table.getElementsByTagName("tr");
  1462. for (var i = 0; i < trs.length; i++) {
  1463. var rowspan = trs[i].getAttribute("rowspan") || 0;
  1464. if (rowspan) {
  1465. rowspan = parseInt(rowspan, 10);
  1466. }
  1467. rows += (rowspan || 1);
  1468. // Now look for column-related info
  1469. var columnsInThisRow = 0;
  1470. var cells = trs[i].getElementsByTagName("td");
  1471. for (var j = 0; j < cells.length; j++) {
  1472. var colspan = cells[j].getAttribute("colspan") || 0;
  1473. if (colspan) {
  1474. colspan = parseInt(colspan, 10);
  1475. }
  1476. columnsInThisRow += (colspan || 1);
  1477. }
  1478. columns = Math.max(columns, columnsInThisRow);
  1479. }
  1480. return {rows: rows, columns: columns};
  1481. },
  1482. /**
  1483. * Look for 'data' (as opposed to 'layout') tables, for which we use
  1484. * similar checks as
  1485. * https://dxr.mozilla.org/mozilla-central/rev/71224049c0b52ab190564d3ea0eab089a159a4cf/accessible/html/HTMLTableAccessible.cpp#920
  1486. */
  1487. _markDataTables: function(root) {
  1488. var tables = root.getElementsByTagName("table");
  1489. for (var i = 0; i < tables.length; i++) {
  1490. var table = tables[i];
  1491. var role = table.getAttribute("role");
  1492. if (role == "presentation") {
  1493. table._readabilityDataTable = false;
  1494. continue;
  1495. }
  1496. var datatable = table.getAttribute("datatable");
  1497. if (datatable == "0") {
  1498. table._readabilityDataTable = false;
  1499. continue;
  1500. }
  1501. var summary = table.getAttribute("summary");
  1502. if (summary) {
  1503. table._readabilityDataTable = true;
  1504. continue;
  1505. }
  1506. var caption = table.getElementsByTagName("caption")[0];
  1507. if (caption && caption.childNodes.length > 0) {
  1508. table._readabilityDataTable = true;
  1509. continue;
  1510. }
  1511. // If the table has a descendant with any of these tags, consider a data table:
  1512. var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"];
  1513. var descendantExists = function(tag) {
  1514. return !!table.getElementsByTagName(tag)[0];
  1515. };
  1516. if (dataTableDescendants.some(descendantExists)) {
  1517. this.log("Data table because found data-y descendant");
  1518. table._readabilityDataTable = true;
  1519. continue;
  1520. }
  1521. // Nested tables indicate a layout table:
  1522. if (table.getElementsByTagName("table")[0]) {
  1523. table._readabilityDataTable = false;
  1524. continue;
  1525. }
  1526. var sizeInfo = this._getRowAndColumnCount(table);
  1527. if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) {
  1528. table._readabilityDataTable = true;
  1529. continue;
  1530. }
  1531. // Now just go by size entirely:
  1532. table._readabilityDataTable = sizeInfo.rows * sizeInfo.columns > 10;
  1533. }
  1534. },
  1535. /* convert images and figures that have properties like data-src into images that can be loaded without JS */
  1536. _fixLazyImages: function (root) {
  1537. this._forEachNode(this._getAllNodesWithTag(root, ["img", "picture", "figure"]), function (elem) {
  1538. // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580
  1539. if ((!elem.src && (!elem.srcset || elem.srcset == "null")) || elem.className.toLowerCase().indexOf("lazy") !== -1) {
  1540. for (var i = 0; i < elem.attributes.length; i++) {
  1541. var attr = elem.attributes[i];
  1542. if (attr.name === "src" || attr.name === "srcset") {
  1543. continue;
  1544. }
  1545. var copyTo = null;
  1546. if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) {
  1547. copyTo = "srcset";
  1548. } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) {
  1549. copyTo = "src";
  1550. }
  1551. if (copyTo) {
  1552. //if this is an img or picture, set the attribute directly
  1553. if (elem.tagName === "IMG" || elem.tagName === "PICTURE") {
  1554. elem.setAttribute(copyTo, attr.value);
  1555. } else if (elem.tagName === "FIGURE" && !this._getAllNodesWithTag(elem, ["img", "picture"]).length) {
  1556. //if the item is a <figure> that does not contain an image or picture, create one and place it inside the figure
  1557. //see the nytimes-3 testcase for an example
  1558. var img = this._doc.createElement("img");
  1559. img.setAttribute(copyTo, attr.value);
  1560. elem.appendChild(img);
  1561. }
  1562. }
  1563. }
  1564. }
  1565. });
  1566. },
  1567. /**
  1568. * Clean an element of all tags of type "tag" if they look fishy.
  1569. * "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc.
  1570. *
  1571. * @return void
  1572. **/
  1573. _cleanConditionally: function(e, tag) {
  1574. if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY))
  1575. return;
  1576. var isList = tag === "ul" || tag === "ol";
  1577. // Gather counts for other typical elements embedded within.
  1578. // Traverse backwards so we can remove nodes at the same time
  1579. // without effecting the traversal.
  1580. //
  1581. // TODO: Consider taking into account original contentScore here.
  1582. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(node) {
  1583. // First check if this node IS data table, in which case don't remove it.
  1584. var isDataTable = function(t) {
  1585. return t._readabilityDataTable;
  1586. };
  1587. if (tag === "table" && isDataTable(node)) {
  1588. return false;
  1589. }
  1590. // Next check if we're inside a data table, in which case don't remove it as well.
  1591. if (this._hasAncestorTag(node, "table", -1, isDataTable)) {
  1592. return false;
  1593. }
  1594. var weight = this._getClassWeight(node);
  1595. var contentScore = 0;
  1596. this.log("Cleaning Conditionally", node);
  1597. if (weight + contentScore < 0) {
  1598. return true;
  1599. }
  1600. if (this._getCharCount(node, ",") < 10) {
  1601. // If there are not very many commas, and the number of
  1602. // non-paragraph elements is more than paragraphs or other
  1603. // ominous signs, remove the element.
  1604. var p = node.getElementsByTagName("p").length;
  1605. var img = node.getElementsByTagName("img").length;
  1606. var li = node.getElementsByTagName("li").length - 100;
  1607. var input = node.getElementsByTagName("input").length;
  1608. var embedCount = 0;
  1609. var embeds = this._getAllNodesWithTag(node, ["object", "embed", "iframe"]);
  1610. for (var i = 0; i < embeds.length; i++) {
  1611. // If this embed has attribute that matches video regex, don't delete it.
  1612. for (var j = 0; j < embeds[i].attributes.length; j++) {
  1613. if (this.REGEXPS.videos.test(embeds[i].attributes[j].value)) {
  1614. return false;
  1615. }
  1616. }
  1617. // For embed with <object> tag, check inner HTML as well.
  1618. if (embeds[i].tagName === "object" && this.REGEXPS.videos.test(embeds[i].innerHTML)) {
  1619. return false;
  1620. }
  1621. embedCount++;
  1622. }
  1623. var linkDensity = this._getLinkDensity(node);
  1624. var contentLength = this._getInnerText(node).length;
  1625. var haveToRemove =
  1626. (img > 1 && p / img < 0.5 && !this._hasAncestorTag(node, "figure")) ||
  1627. (!isList && li > p) ||
  1628. (input > Math.floor(p/3)) ||
  1629. (!isList && contentLength < 25 && (img === 0 || img > 2) && !this._hasAncestorTag(node, "figure")) ||
  1630. (!isList && weight < 25 && linkDensity > 0.2) ||
  1631. (weight >= 25 && linkDensity > 0.5) ||
  1632. ((embedCount === 1 && contentLength < 75) || embedCount > 1);
  1633. return haveToRemove;
  1634. }
  1635. return false;
  1636. });
  1637. },
  1638. /**
  1639. * Clean out elements that match the specified conditions
  1640. *
  1641. * @param Element
  1642. * @param Function determines whether a node should be removed
  1643. * @return void
  1644. **/
  1645. _cleanMatchedNodes: function(e, filter) {
  1646. var endOfSearchMarkerNode = this._getNextNode(e, true);
  1647. var next = this._getNextNode(e);
  1648. while (next && next != endOfSearchMarkerNode) {
  1649. if (filter.call(this, next, next.className + " " + next.id)) {
  1650. next = this._removeAndGetNext(next);
  1651. } else {
  1652. next = this._getNextNode(next);
  1653. }
  1654. }
  1655. },
  1656. /**
  1657. * Clean out spurious headers from an Element. Checks things like classnames and link density.
  1658. *
  1659. * @param Element
  1660. * @return void
  1661. **/
  1662. _cleanHeaders: function(e) {
  1663. this._removeNodes(this._getAllNodesWithTag(e, ["h1", "h2"]), function (header) {
  1664. return this._getClassWeight(header) < 0;
  1665. });
  1666. },
  1667. _flagIsActive: function(flag) {
  1668. return (this._flags & flag) > 0;
  1669. },
  1670. _removeFlag: function(flag) {
  1671. this._flags = this._flags & ~flag;
  1672. },
  1673. _isProbablyVisible: function(node) {
  1674. // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes.
  1675. return (!node.style || node.style.display != "none")
  1676. && !node.hasAttribute("hidden")
  1677. //check for "fallback-image" so that wikimedia math images are displayed
  1678. && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1));
  1679. },
  1680. /**
  1681. * Runs readability.
  1682. *
  1683. * Workflow:
  1684. * 1. Prep the document by removing script tags, css, etc.
  1685. * 2. Build readability's DOM tree.
  1686. * 3. Grab the article content from the current dom tree.
  1687. * 4. Replace the current DOM tree with the new one.
  1688. * 5. Read peacefully.
  1689. *
  1690. * @return void
  1691. **/
  1692. parse: function () {
  1693. // Avoid parsing too large documents, as per configuration option
  1694. if (this._maxElemsToParse > 0) {
  1695. var numTags = this._doc.getElementsByTagName("*").length;
  1696. if (numTags > this._maxElemsToParse) {
  1697. throw new Error("Aborting parsing document; " + numTags + " elements found");
  1698. }
  1699. }
  1700. // Unwrap image from noscript
  1701. this._unwrapNoscriptImages(this._doc);
  1702. // Remove script tags from the document.
  1703. this._removeScripts(this._doc);
  1704. this._prepDocument();
  1705. var metadata = this._getArticleMetadata();
  1706. this._articleTitle = metadata.title;
  1707. var articleContent = this._grabArticle();
  1708. if (!articleContent)
  1709. return null;
  1710. this.log("Grabbed: " + articleContent.innerHTML);
  1711. this._postProcessContent(articleContent);
  1712. // If we haven't found an excerpt in the article's metadata, use the article's
  1713. // first paragraph as the excerpt. This is used for displaying a preview of
  1714. // the article's content.
  1715. if (!metadata.excerpt) {
  1716. var paragraphs = articleContent.getElementsByTagName("p");
  1717. if (paragraphs.length > 0) {
  1718. metadata.excerpt = paragraphs[0].textContent.trim();
  1719. }
  1720. }
  1721. var textContent = articleContent.textContent;
  1722. return {
  1723. title: this._articleTitle,
  1724. byline: metadata.byline || this._articleByline,
  1725. dir: this._articleDir,
  1726. content: articleContent.innerHTML,
  1727. textContent: textContent,
  1728. length: textContent.length,
  1729. excerpt: metadata.excerpt,
  1730. siteName: metadata.siteName || this._articleSiteName
  1731. };
  1732. }
  1733. };
  1734. if (typeof module === "object") {
  1735. module.exports = Readability;
  1736. }