Readability.js 81 KB

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