Readability.js 79 KB

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