Readability.js 70 KB

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