Readability.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261
  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.firstChild) {
  354. container.appendChild(link.firstChild);
  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. while (page.firstChild) {
  951. this.log("Moving child out:", page.firstChild);
  952. topCandidate.appendChild(page.firstChild);
  953. }
  954. page.appendChild(topCandidate);
  955. this._initializeNode(topCandidate);
  956. } else if (topCandidate) {
  957. // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
  958. // and whose scores are quite closed with current `topCandidate` node.
  959. var alternativeCandidateAncestors = [];
  960. for (var i = 1; i < topCandidates.length; i++) {
  961. if (topCandidates[i].readability.contentScore / topCandidate.readability.contentScore >= 0.75) {
  962. alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i]));
  963. }
  964. }
  965. var MINIMUM_TOPCANDIDATES = 3;
  966. if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) {
  967. parentOfTopCandidate = topCandidate.parentNode;
  968. while (parentOfTopCandidate.tagName !== "BODY") {
  969. var listsContainingThisAncestor = 0;
  970. for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) {
  971. listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate));
  972. }
  973. if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) {
  974. topCandidate = parentOfTopCandidate;
  975. break;
  976. }
  977. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  978. }
  979. }
  980. if (!topCandidate.readability) {
  981. this._initializeNode(topCandidate);
  982. }
  983. // Because of our bonus system, parents of candidates might have scores
  984. // themselves. They get half of the node. There won't be nodes with higher
  985. // scores than our topCandidate, but if we see the score going *up* in the first
  986. // few steps up the tree, that's a decent sign that there might be more content
  987. // lurking in other places that we want to unify in. The sibling stuff
  988. // below does some of that - but only if we've looked high enough up the DOM
  989. // tree.
  990. parentOfTopCandidate = topCandidate.parentNode;
  991. var lastScore = topCandidate.readability.contentScore;
  992. // The scores shouldn't get too low.
  993. var scoreThreshold = lastScore / 3;
  994. while (parentOfTopCandidate.tagName !== "BODY") {
  995. if (!parentOfTopCandidate.readability) {
  996. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  997. continue;
  998. }
  999. var parentScore = parentOfTopCandidate.readability.contentScore;
  1000. if (parentScore < scoreThreshold)
  1001. break;
  1002. if (parentScore > lastScore) {
  1003. // Alright! We found a better parent to use.
  1004. topCandidate = parentOfTopCandidate;
  1005. break;
  1006. }
  1007. lastScore = parentOfTopCandidate.readability.contentScore;
  1008. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  1009. }
  1010. // If the top candidate is the only child, use parent instead. This will help sibling
  1011. // joining logic when adjacent content is actually located in parent's sibling node.
  1012. parentOfTopCandidate = topCandidate.parentNode;
  1013. while (parentOfTopCandidate.tagName != "BODY" && parentOfTopCandidate.children.length == 1) {
  1014. topCandidate = parentOfTopCandidate;
  1015. parentOfTopCandidate = topCandidate.parentNode;
  1016. }
  1017. if (!topCandidate.readability) {
  1018. this._initializeNode(topCandidate);
  1019. }
  1020. }
  1021. // Now that we have the top candidate, look through its siblings for content
  1022. // that might also be related. Things like preambles, content split by ads
  1023. // that we removed, etc.
  1024. var articleContent = doc.createElement("DIV");
  1025. if (isPaging)
  1026. articleContent.id = "readability-content";
  1027. var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2);
  1028. // Keep potential top candidate's parent node to try to get text direction of it later.
  1029. parentOfTopCandidate = topCandidate.parentNode;
  1030. var siblings = parentOfTopCandidate.children;
  1031. for (var s = 0, sl = siblings.length; s < sl; s++) {
  1032. var sibling = siblings[s];
  1033. var append = false;
  1034. this.log("Looking at sibling node:", sibling, sibling.readability ? ("with score " + sibling.readability.contentScore) : "");
  1035. this.log("Sibling has score", sibling.readability ? sibling.readability.contentScore : "Unknown");
  1036. if (sibling === topCandidate) {
  1037. append = true;
  1038. } else {
  1039. var contentBonus = 0;
  1040. // Give a bonus if sibling nodes and top candidates have the example same classname
  1041. if (sibling.className === topCandidate.className && topCandidate.className !== "")
  1042. contentBonus += topCandidate.readability.contentScore * 0.2;
  1043. if (sibling.readability &&
  1044. ((sibling.readability.contentScore + contentBonus) >= siblingScoreThreshold)) {
  1045. append = true;
  1046. } else if (sibling.nodeName === "P") {
  1047. var linkDensity = this._getLinkDensity(sibling);
  1048. var nodeContent = this._getInnerText(sibling);
  1049. var nodeLength = nodeContent.length;
  1050. if (nodeLength > 80 && linkDensity < 0.25) {
  1051. append = true;
  1052. } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 &&
  1053. nodeContent.search(/\.( |$)/) !== -1) {
  1054. append = true;
  1055. }
  1056. }
  1057. }
  1058. if (append) {
  1059. this.log("Appending node:", sibling);
  1060. if (this.ALTER_TO_DIV_EXCEPTIONS.indexOf(sibling.nodeName) === -1) {
  1061. // We have a node that isn't a common block level element, like a form or td tag.
  1062. // Turn it into a div so it doesn't get filtered out later by accident.
  1063. this.log("Altering sibling:", sibling, "to div.");
  1064. sibling = this._setNodeTag(sibling, "DIV");
  1065. }
  1066. articleContent.appendChild(sibling);
  1067. // Fetch children again to make it compatible
  1068. // with DOM parsers without live collection support.
  1069. siblings = parentOfTopCandidate.children;
  1070. // siblings is a reference to the children array, and
  1071. // sibling is removed from the array when we call appendChild().
  1072. // As a result, we must revisit this index since the nodes
  1073. // have been shifted.
  1074. s -= 1;
  1075. sl -= 1;
  1076. }
  1077. }
  1078. if (this._debug)
  1079. this.log("Article content pre-prep: " + articleContent.innerHTML);
  1080. // So we have all of the content that we need. Now we clean it up for presentation.
  1081. this._prepArticle(articleContent);
  1082. if (this._debug)
  1083. this.log("Article content post-prep: " + articleContent.innerHTML);
  1084. if (neededToCreateTopCandidate) {
  1085. // We already created a fake div thing, and there wouldn't have been any siblings left
  1086. // for the previous loop, so there's no point trying to create a new div, and then
  1087. // move all the children over. Just assign IDs and class names here. No need to append
  1088. // because that already happened anyway.
  1089. topCandidate.id = "readability-page-1";
  1090. topCandidate.className = "page";
  1091. } else {
  1092. var div = doc.createElement("DIV");
  1093. div.id = "readability-page-1";
  1094. div.className = "page";
  1095. while (articleContent.firstChild) {
  1096. div.appendChild(articleContent.firstChild);
  1097. }
  1098. articleContent.appendChild(div);
  1099. }
  1100. if (this._debug)
  1101. this.log("Article content after paging: " + articleContent.innerHTML);
  1102. var parseSuccessful = true;
  1103. // Now that we've gone through the full algorithm, check to see if
  1104. // we got any meaningful content. If we didn't, we may need to re-run
  1105. // grabArticle with different flags set. This gives us a higher likelihood of
  1106. // finding the content, and the sieve approach gives us a higher likelihood of
  1107. // finding the -right- content.
  1108. var textLength = this._getInnerText(articleContent, true).length;
  1109. if (textLength < this._charThreshold) {
  1110. parseSuccessful = false;
  1111. page.innerHTML = pageCacheHtml;
  1112. if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) {
  1113. this._removeFlag(this.FLAG_STRIP_UNLIKELYS);
  1114. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1115. } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
  1116. this._removeFlag(this.FLAG_WEIGHT_CLASSES);
  1117. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1118. } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
  1119. this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);
  1120. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1121. } else {
  1122. this._attempts.push({articleContent: articleContent, textLength: textLength});
  1123. // No luck after removing flags, just return the longest text we found during the different loops
  1124. this._attempts.sort(function (a, b) {
  1125. return b.textLength - a.textLength;
  1126. });
  1127. // But first check if we actually have something
  1128. if (!this._attempts[0].textLength) {
  1129. return null;
  1130. }
  1131. articleContent = this._attempts[0].articleContent;
  1132. parseSuccessful = true;
  1133. }
  1134. }
  1135. if (parseSuccessful) {
  1136. // Find out text direction from ancestors of final top candidate.
  1137. var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate));
  1138. this._someNode(ancestors, function(ancestor) {
  1139. if (!ancestor.tagName)
  1140. return false;
  1141. var articleDir = ancestor.getAttribute("dir");
  1142. if (articleDir) {
  1143. this._articleDir = articleDir;
  1144. return true;
  1145. }
  1146. return false;
  1147. });
  1148. return articleContent;
  1149. }
  1150. }
  1151. },
  1152. /**
  1153. * Check whether the input string could be a byline.
  1154. * This verifies that the input is a string, and that the length
  1155. * is less than 100 chars.
  1156. *
  1157. * @param possibleByline {string} - a string to check whether its a byline.
  1158. * @return Boolean - whether the input string is a byline.
  1159. */
  1160. _isValidByline: function(byline) {
  1161. if (typeof byline == "string" || byline instanceof String) {
  1162. byline = byline.trim();
  1163. return (byline.length > 0) && (byline.length < 100);
  1164. }
  1165. return false;
  1166. },
  1167. /**
  1168. * Converts some of the common HTML entities in string to their corresponding characters.
  1169. *
  1170. * @param str {string} - a string to unescape.
  1171. * @return string without HTML entity.
  1172. */
  1173. _unescapeHtmlEntities: function(str) {
  1174. if (!str) {
  1175. return str;
  1176. }
  1177. var htmlEscapeMap = this.HTML_ESCAPE_MAP;
  1178. return str.replace(/&(quot|amp|apos|lt|gt);/g, function(_, tag) {
  1179. return htmlEscapeMap[tag];
  1180. }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(_, hex, numStr) {
  1181. var num = parseInt(hex || numStr, hex ? 16 : 10);
  1182. return String.fromCharCode(num);
  1183. });
  1184. },
  1185. /**
  1186. * Try to extract metadata from JSON-LD object.
  1187. * For now, only Schema.org objects of type Article or its subtypes are supported.
  1188. * @return Object with any metadata that could be extracted (possibly none)
  1189. */
  1190. _getJSONLD: function (doc) {
  1191. var scripts = this._getAllNodesWithTag(doc, ["script"]);
  1192. var jsonLdElement = this._findNode(scripts, function(el) {
  1193. return el.getAttribute("type") === "application/ld+json";
  1194. });
  1195. if (jsonLdElement) {
  1196. try {
  1197. // Strip CDATA markers if present
  1198. var content = jsonLdElement.textContent.replace(/^\s*<!\[CDATA\[|\]\]>\s*$/g, "");
  1199. var parsed = JSON.parse(content);
  1200. var metadata = {};
  1201. if (
  1202. !parsed["@context"] ||
  1203. !parsed["@context"].match(/^https?\:\/\/schema\.org$/)
  1204. ) {
  1205. return metadata;
  1206. }
  1207. if (!parsed["@type"] && Array.isArray(parsed["@graph"])) {
  1208. parsed = parsed["@graph"].find(function(it) {
  1209. return (it["@type"] || "").match(
  1210. this.REGEXPS.jsonLdArticleTypes
  1211. );
  1212. });
  1213. }
  1214. if (
  1215. !parsed ||
  1216. !parsed["@type"] ||
  1217. !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)
  1218. ) {
  1219. return metadata;
  1220. }
  1221. if (typeof parsed.name === "string") {
  1222. metadata.title = parsed.name.trim();
  1223. } else if (typeof parsed.headline === "string") {
  1224. metadata.title = parsed.headline.trim();
  1225. }
  1226. if (parsed.author) {
  1227. if (typeof parsed.author.name === "string") {
  1228. metadata.byline = parsed.author.name.trim();
  1229. } else if (Array.isArray(parsed.author) && parsed.author[0] && typeof parsed.author[0].name === "string") {
  1230. metadata.byline = parsed.author
  1231. .filter(function(author) {
  1232. return author && typeof author.name === "string";
  1233. })
  1234. .map(function(author) {
  1235. return author.name.trim();
  1236. })
  1237. .join(", ");
  1238. }
  1239. }
  1240. if (typeof parsed.description === "string") {
  1241. metadata.excerpt = parsed.description.trim();
  1242. }
  1243. if (
  1244. parsed.publisher &&
  1245. typeof parsed.publisher.name === "string"
  1246. ) {
  1247. metadata.siteName = parsed.publisher.name.trim();
  1248. }
  1249. return metadata;
  1250. } catch (err) {
  1251. this.log(err.message);
  1252. }
  1253. }
  1254. return {};
  1255. },
  1256. /**
  1257. * Attempts to get excerpt and byline metadata for the article.
  1258. *
  1259. * @param {Object} jsonld — object containing any metadata that
  1260. * could be extracted from JSON-LD object.
  1261. *
  1262. * @return Object with optional "excerpt" and "byline" properties
  1263. */
  1264. _getArticleMetadata: function(jsonld) {
  1265. var metadata = {};
  1266. var values = {};
  1267. var metaElements = this._doc.getElementsByTagName("meta");
  1268. // property is a space-separated list of values
  1269. var propertyPattern = /\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|site_name)\s*/gi;
  1270. // name is a single value
  1271. var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;
  1272. // Find description tags.
  1273. this._forEachNode(metaElements, function(element) {
  1274. var elementName = element.getAttribute("name");
  1275. var elementProperty = element.getAttribute("property");
  1276. var content = element.getAttribute("content");
  1277. if (!content) {
  1278. return;
  1279. }
  1280. var matches = null;
  1281. var name = null;
  1282. if (elementProperty) {
  1283. matches = elementProperty.match(propertyPattern);
  1284. if (matches) {
  1285. // Convert to lowercase, and remove any whitespace
  1286. // so we can match below.
  1287. name = matches[0].toLowerCase().replace(/\s/g, "");
  1288. // multiple authors
  1289. values[name] = content.trim();
  1290. }
  1291. }
  1292. if (!matches && elementName && namePattern.test(elementName)) {
  1293. name = elementName;
  1294. if (content) {
  1295. // Convert to lowercase, remove any whitespace, and convert dots
  1296. // to colons so we can match below.
  1297. name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":");
  1298. values[name] = content.trim();
  1299. }
  1300. }
  1301. });
  1302. // get title
  1303. metadata.title = jsonld.title ||
  1304. values["dc:title"] ||
  1305. values["dcterm:title"] ||
  1306. values["og:title"] ||
  1307. values["weibo:article:title"] ||
  1308. values["weibo:webpage:title"] ||
  1309. values["title"] ||
  1310. values["twitter:title"];
  1311. if (!metadata.title) {
  1312. metadata.title = this._getArticleTitle();
  1313. }
  1314. // get author
  1315. metadata.byline = jsonld.byline ||
  1316. values["dc:creator"] ||
  1317. values["dcterm:creator"] ||
  1318. values["author"];
  1319. // get description
  1320. metadata.excerpt = jsonld.excerpt ||
  1321. values["dc:description"] ||
  1322. values["dcterm:description"] ||
  1323. values["og:description"] ||
  1324. values["weibo:article:description"] ||
  1325. values["weibo:webpage:description"] ||
  1326. values["description"] ||
  1327. values["twitter:description"];
  1328. // get site name
  1329. metadata.siteName = jsonld.siteName ||
  1330. values["og:site_name"];
  1331. // in many sites the meta value is escaped with HTML entities,
  1332. // so here we need to unescape it
  1333. metadata.title = this._unescapeHtmlEntities(metadata.title);
  1334. metadata.byline = this._unescapeHtmlEntities(metadata.byline);
  1335. metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt);
  1336. metadata.siteName = this._unescapeHtmlEntities(metadata.siteName);
  1337. return metadata;
  1338. },
  1339. /**
  1340. * Check if node is image, or if node contains exactly only one image
  1341. * whether as a direct child or as its descendants.
  1342. *
  1343. * @param Element
  1344. **/
  1345. _isSingleImage: function(node) {
  1346. if (node.tagName === "IMG") {
  1347. return true;
  1348. }
  1349. if (node.children.length !== 1 || node.textContent.trim() !== "") {
  1350. return false;
  1351. }
  1352. return this._isSingleImage(node.children[0]);
  1353. },
  1354. /**
  1355. * Find all <noscript> that are located after <img> nodes, and which contain only one
  1356. * <img> element. Replace the first image with the image from inside the <noscript> tag,
  1357. * and remove the <noscript> tag. This improves the quality of the images we use on
  1358. * some sites (e.g. Medium).
  1359. *
  1360. * @param Element
  1361. **/
  1362. _unwrapNoscriptImages: function(doc) {
  1363. // Find img without source or attributes that might contains image, and remove it.
  1364. // This is done to prevent a placeholder img is replaced by img from noscript in next step.
  1365. var imgs = Array.from(doc.getElementsByTagName("img"));
  1366. this._forEachNode(imgs, function(img) {
  1367. for (var i = 0; i < img.attributes.length; i++) {
  1368. var attr = img.attributes[i];
  1369. switch (attr.name) {
  1370. case "src":
  1371. case "srcset":
  1372. case "data-src":
  1373. case "data-srcset":
  1374. return;
  1375. }
  1376. if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1377. return;
  1378. }
  1379. }
  1380. img.parentNode.removeChild(img);
  1381. });
  1382. // Next find noscript and try to extract its image
  1383. var noscripts = Array.from(doc.getElementsByTagName("noscript"));
  1384. this._forEachNode(noscripts, function(noscript) {
  1385. // Parse content of noscript and make sure it only contains image
  1386. var tmp = doc.createElement("div");
  1387. tmp.innerHTML = noscript.innerHTML;
  1388. if (!this._isSingleImage(tmp)) {
  1389. return;
  1390. }
  1391. // If noscript has previous sibling and it only contains image,
  1392. // replace it with noscript content. However we also keep old
  1393. // attributes that might contains image.
  1394. var prevElement = noscript.previousElementSibling;
  1395. if (prevElement && this._isSingleImage(prevElement)) {
  1396. var prevImg = prevElement;
  1397. if (prevImg.tagName !== "IMG") {
  1398. prevImg = prevElement.getElementsByTagName("img")[0];
  1399. }
  1400. var newImg = tmp.getElementsByTagName("img")[0];
  1401. for (var i = 0; i < prevImg.attributes.length; i++) {
  1402. var attr = prevImg.attributes[i];
  1403. if (attr.value === "") {
  1404. continue;
  1405. }
  1406. if (attr.name === "src" || attr.name === "srcset" || /\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1407. if (newImg.getAttribute(attr.name) === attr.value) {
  1408. continue;
  1409. }
  1410. var attrName = attr.name;
  1411. if (newImg.hasAttribute(attrName)) {
  1412. attrName = "data-old-" + attrName;
  1413. }
  1414. newImg.setAttribute(attrName, attr.value);
  1415. }
  1416. }
  1417. noscript.parentNode.replaceChild(tmp.firstElementChild, prevElement);
  1418. }
  1419. });
  1420. },
  1421. /**
  1422. * Removes script tags from the document.
  1423. *
  1424. * @param Element
  1425. **/
  1426. _removeScripts: function(doc) {
  1427. this._removeNodes(this._getAllNodesWithTag(doc, ["script"]), function(scriptNode) {
  1428. scriptNode.nodeValue = "";
  1429. scriptNode.removeAttribute("src");
  1430. return true;
  1431. });
  1432. this._removeNodes(this._getAllNodesWithTag(doc, ["noscript"]));
  1433. },
  1434. /**
  1435. * Check if this node has only whitespace and a single element with given tag
  1436. * Returns false if the DIV node contains non-empty text nodes
  1437. * or if it contains no element with given tag or more than 1 element.
  1438. *
  1439. * @param Element
  1440. * @param string tag of child element
  1441. **/
  1442. _hasSingleTagInsideElement: function(element, tag) {
  1443. // There should be exactly 1 element child with given tag
  1444. if (element.children.length != 1 || element.children[0].tagName !== tag) {
  1445. return false;
  1446. }
  1447. // And there should be no text nodes with real content
  1448. return !this._someNode(element.childNodes, function(node) {
  1449. return node.nodeType === this.TEXT_NODE &&
  1450. this.REGEXPS.hasContent.test(node.textContent);
  1451. });
  1452. },
  1453. _isElementWithoutContent: function(node) {
  1454. return node.nodeType === this.ELEMENT_NODE &&
  1455. node.textContent.trim().length == 0 &&
  1456. (node.children.length == 0 ||
  1457. node.children.length == node.getElementsByTagName("br").length + node.getElementsByTagName("hr").length);
  1458. },
  1459. /**
  1460. * Determine whether element has any children block level elements.
  1461. *
  1462. * @param Element
  1463. */
  1464. _hasChildBlockElement: function (element) {
  1465. return this._someNode(element.childNodes, function(node) {
  1466. return this.DIV_TO_P_ELEMS.has(node.tagName) ||
  1467. this._hasChildBlockElement(node);
  1468. });
  1469. },
  1470. /***
  1471. * Determine if a node qualifies as phrasing content.
  1472. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
  1473. **/
  1474. _isPhrasingContent: function(node) {
  1475. return node.nodeType === this.TEXT_NODE || this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 ||
  1476. ((node.tagName === "A" || node.tagName === "DEL" || node.tagName === "INS") &&
  1477. this._everyNode(node.childNodes, this._isPhrasingContent));
  1478. },
  1479. _isWhitespace: function(node) {
  1480. return (node.nodeType === this.TEXT_NODE && node.textContent.trim().length === 0) ||
  1481. (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR");
  1482. },
  1483. /**
  1484. * Get the inner text of a node - cross browser compatibly.
  1485. * This also strips out any excess whitespace to be found.
  1486. *
  1487. * @param Element
  1488. * @param Boolean normalizeSpaces (default: true)
  1489. * @return string
  1490. **/
  1491. _getInnerText: function(e, normalizeSpaces) {
  1492. normalizeSpaces = (typeof normalizeSpaces === "undefined") ? true : normalizeSpaces;
  1493. var textContent = e.textContent.trim();
  1494. if (normalizeSpaces) {
  1495. return textContent.replace(this.REGEXPS.normalize, " ");
  1496. }
  1497. return textContent;
  1498. },
  1499. /**
  1500. * Get the number of times a string s appears in the node e.
  1501. *
  1502. * @param Element
  1503. * @param string - what to split on. Default is ","
  1504. * @return number (integer)
  1505. **/
  1506. _getCharCount: function(e, s) {
  1507. s = s || ",";
  1508. return this._getInnerText(e).split(s).length - 1;
  1509. },
  1510. /**
  1511. * Remove the style attribute on every e and under.
  1512. * TODO: Test if getElementsByTagName(*) is faster.
  1513. *
  1514. * @param Element
  1515. * @return void
  1516. **/
  1517. _cleanStyles: function(e) {
  1518. if (!e || e.tagName.toLowerCase() === "svg")
  1519. return;
  1520. // Remove `style` and deprecated presentational attributes
  1521. for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) {
  1522. e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);
  1523. }
  1524. if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.indexOf(e.tagName) !== -1) {
  1525. e.removeAttribute("width");
  1526. e.removeAttribute("height");
  1527. }
  1528. var cur = e.firstElementChild;
  1529. while (cur !== null) {
  1530. this._cleanStyles(cur);
  1531. cur = cur.nextElementSibling;
  1532. }
  1533. },
  1534. /**
  1535. * Get the density of links as a percentage of the content
  1536. * This is the amount of text that is inside a link divided by the total text in the node.
  1537. *
  1538. * @param Element
  1539. * @return number (float)
  1540. **/
  1541. _getLinkDensity: function(element) {
  1542. var textLength = this._getInnerText(element).length;
  1543. if (textLength === 0)
  1544. return 0;
  1545. var linkLength = 0;
  1546. // XXX implement _reduceNodeList?
  1547. this._forEachNode(element.getElementsByTagName("a"), function(linkNode) {
  1548. var href = linkNode.getAttribute("href");
  1549. var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1;
  1550. linkLength += this._getInnerText(linkNode).length * coefficient;
  1551. });
  1552. return linkLength / textLength;
  1553. },
  1554. /**
  1555. * Get an elements class/id weight. Uses regular expressions to tell if this
  1556. * element looks good or bad.
  1557. *
  1558. * @param Element
  1559. * @return number (Integer)
  1560. **/
  1561. _getClassWeight: function(e) {
  1562. if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES))
  1563. return 0;
  1564. var weight = 0;
  1565. // Look for a special classname
  1566. if (typeof(e.className) === "string" && e.className !== "") {
  1567. if (this.REGEXPS.negative.test(e.className))
  1568. weight -= 25;
  1569. if (this.REGEXPS.positive.test(e.className))
  1570. weight += 25;
  1571. }
  1572. // Look for a special ID
  1573. if (typeof(e.id) === "string" && e.id !== "") {
  1574. if (this.REGEXPS.negative.test(e.id))
  1575. weight -= 25;
  1576. if (this.REGEXPS.positive.test(e.id))
  1577. weight += 25;
  1578. }
  1579. return weight;
  1580. },
  1581. /**
  1582. * Clean a node of all elements of type "tag".
  1583. * (Unless it's a youtube/vimeo video. People love movies.)
  1584. *
  1585. * @param Element
  1586. * @param string tag to clean
  1587. * @return void
  1588. **/
  1589. _clean: function(e, tag) {
  1590. var isEmbed = ["object", "embed", "iframe"].indexOf(tag) !== -1;
  1591. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(element) {
  1592. // Allow youtube and vimeo videos through as people usually want to see those.
  1593. if (isEmbed) {
  1594. // First, check the elements attributes to see if any of them contain youtube or vimeo
  1595. for (var i = 0; i < element.attributes.length; i++) {
  1596. if (this.REGEXPS.videos.test(element.attributes[i].value)) {
  1597. return false;
  1598. }
  1599. }
  1600. // For embed with <object> tag, check inner HTML as well.
  1601. if (element.tagName === "object" && this.REGEXPS.videos.test(element.innerHTML)) {
  1602. return false;
  1603. }
  1604. }
  1605. return true;
  1606. });
  1607. },
  1608. /**
  1609. * Check if a given node has one of its ancestor tag name matching the
  1610. * provided one.
  1611. * @param HTMLElement node
  1612. * @param String tagName
  1613. * @param Number maxDepth
  1614. * @param Function filterFn a filter to invoke to determine whether this node 'counts'
  1615. * @return Boolean
  1616. */
  1617. _hasAncestorTag: function(node, tagName, maxDepth, filterFn) {
  1618. maxDepth = maxDepth || 3;
  1619. tagName = tagName.toUpperCase();
  1620. var depth = 0;
  1621. while (node.parentNode) {
  1622. if (maxDepth > 0 && depth > maxDepth)
  1623. return false;
  1624. if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode)))
  1625. return true;
  1626. node = node.parentNode;
  1627. depth++;
  1628. }
  1629. return false;
  1630. },
  1631. /**
  1632. * Return an object indicating how many rows and columns this table has.
  1633. */
  1634. _getRowAndColumnCount: function(table) {
  1635. var rows = 0;
  1636. var columns = 0;
  1637. var trs = table.getElementsByTagName("tr");
  1638. for (var i = 0; i < trs.length; i++) {
  1639. var rowspan = trs[i].getAttribute("rowspan") || 0;
  1640. if (rowspan) {
  1641. rowspan = parseInt(rowspan, 10);
  1642. }
  1643. rows += (rowspan || 1);
  1644. // Now look for column-related info
  1645. var columnsInThisRow = 0;
  1646. var cells = trs[i].getElementsByTagName("td");
  1647. for (var j = 0; j < cells.length; j++) {
  1648. var colspan = cells[j].getAttribute("colspan") || 0;
  1649. if (colspan) {
  1650. colspan = parseInt(colspan, 10);
  1651. }
  1652. columnsInThisRow += (colspan || 1);
  1653. }
  1654. columns = Math.max(columns, columnsInThisRow);
  1655. }
  1656. return {rows: rows, columns: columns};
  1657. },
  1658. /**
  1659. * Look for 'data' (as opposed to 'layout') tables, for which we use
  1660. * similar checks as
  1661. * https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/accessible/generic/TableAccessible.cpp#19
  1662. */
  1663. _markDataTables: function(root) {
  1664. var tables = root.getElementsByTagName("table");
  1665. for (var i = 0; i < tables.length; i++) {
  1666. var table = tables[i];
  1667. var role = table.getAttribute("role");
  1668. if (role == "presentation") {
  1669. table._readabilityDataTable = false;
  1670. continue;
  1671. }
  1672. var datatable = table.getAttribute("datatable");
  1673. if (datatable == "0") {
  1674. table._readabilityDataTable = false;
  1675. continue;
  1676. }
  1677. var summary = table.getAttribute("summary");
  1678. if (summary) {
  1679. table._readabilityDataTable = true;
  1680. continue;
  1681. }
  1682. var caption = table.getElementsByTagName("caption")[0];
  1683. if (caption && caption.childNodes.length > 0) {
  1684. table._readabilityDataTable = true;
  1685. continue;
  1686. }
  1687. // If the table has a descendant with any of these tags, consider a data table:
  1688. var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"];
  1689. var descendantExists = function(tag) {
  1690. return !!table.getElementsByTagName(tag)[0];
  1691. };
  1692. if (dataTableDescendants.some(descendantExists)) {
  1693. this.log("Data table because found data-y descendant");
  1694. table._readabilityDataTable = true;
  1695. continue;
  1696. }
  1697. // Nested tables indicate a layout table:
  1698. if (table.getElementsByTagName("table")[0]) {
  1699. table._readabilityDataTable = false;
  1700. continue;
  1701. }
  1702. var sizeInfo = this._getRowAndColumnCount(table);
  1703. if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) {
  1704. table._readabilityDataTable = true;
  1705. continue;
  1706. }
  1707. // Now just go by size entirely:
  1708. table._readabilityDataTable = sizeInfo.rows * sizeInfo.columns > 10;
  1709. }
  1710. },
  1711. /* convert images and figures that have properties like data-src into images that can be loaded without JS */
  1712. _fixLazyImages: function (root) {
  1713. this._forEachNode(this._getAllNodesWithTag(root, ["img", "picture", "figure"]), function (elem) {
  1714. // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute.
  1715. // So, here we check if the data uri is too short, just might as well remove it.
  1716. if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) {
  1717. // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes.
  1718. var parts = this.REGEXPS.b64DataUrl.exec(elem.src);
  1719. if (parts[1] === "image/svg+xml") {
  1720. return;
  1721. }
  1722. // Make sure this element has other attributes which contains image.
  1723. // If it doesn't, then this src is important and shouldn't be removed.
  1724. var srcCouldBeRemoved = false;
  1725. for (var i = 0; i < elem.attributes.length; i++) {
  1726. var attr = elem.attributes[i];
  1727. if (attr.name === "src") {
  1728. continue;
  1729. }
  1730. if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1731. srcCouldBeRemoved = true;
  1732. break;
  1733. }
  1734. }
  1735. // Here we assume if image is less than 100 bytes (or 133B after encoded to base64)
  1736. // it will be too small, therefore it might be placeholder image.
  1737. if (srcCouldBeRemoved) {
  1738. var b64starts = elem.src.search(/base64\s*/i) + 7;
  1739. var b64length = elem.src.length - b64starts;
  1740. if (b64length < 133) {
  1741. elem.removeAttribute("src");
  1742. }
  1743. }
  1744. }
  1745. // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580
  1746. if ((elem.src || (elem.srcset && elem.srcset != "null")) && elem.className.toLowerCase().indexOf("lazy") === -1) {
  1747. return;
  1748. }
  1749. for (var j = 0; j < elem.attributes.length; j++) {
  1750. attr = elem.attributes[j];
  1751. if (attr.name === "src" || attr.name === "srcset" || attr.name === "alt") {
  1752. continue;
  1753. }
  1754. var copyTo = null;
  1755. if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) {
  1756. copyTo = "srcset";
  1757. } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) {
  1758. copyTo = "src";
  1759. }
  1760. if (copyTo) {
  1761. //if this is an img or picture, set the attribute directly
  1762. if (elem.tagName === "IMG" || elem.tagName === "PICTURE") {
  1763. elem.setAttribute(copyTo, attr.value);
  1764. } else if (elem.tagName === "FIGURE" && !this._getAllNodesWithTag(elem, ["img", "picture"]).length) {
  1765. //if the item is a <figure> that does not contain an image or picture, create one and place it inside the figure
  1766. //see the nytimes-3 testcase for an example
  1767. var img = this._doc.createElement("img");
  1768. img.setAttribute(copyTo, attr.value);
  1769. elem.appendChild(img);
  1770. }
  1771. }
  1772. }
  1773. });
  1774. },
  1775. _getTextDensity: function(e, tags) {
  1776. var textLength = this._getInnerText(e, true).length;
  1777. if (textLength === 0) {
  1778. return 0;
  1779. }
  1780. var childrenLength = 0;
  1781. var children = this._getAllNodesWithTag(e, tags);
  1782. this._forEachNode(children, (child) => childrenLength += this._getInnerText(child, true).length);
  1783. return childrenLength / textLength;
  1784. },
  1785. /**
  1786. * Clean an element of all tags of type "tag" if they look fishy.
  1787. * "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc.
  1788. *
  1789. * @return void
  1790. **/
  1791. _cleanConditionally: function(e, tag) {
  1792. if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY))
  1793. return;
  1794. // Gather counts for other typical elements embedded within.
  1795. // Traverse backwards so we can remove nodes at the same time
  1796. // without effecting the traversal.
  1797. //
  1798. // TODO: Consider taking into account original contentScore here.
  1799. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(node) {
  1800. // First check if this node IS data table, in which case don't remove it.
  1801. var isDataTable = function(t) {
  1802. return t._readabilityDataTable;
  1803. };
  1804. var isList = tag === "ul" || tag === "ol";
  1805. if (!isList) {
  1806. var listLength = 0;
  1807. var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]);
  1808. this._forEachNode(listNodes, (list) => listLength += this._getInnerText(list).length);
  1809. isList = listLength / this._getInnerText(node).length > 0.9;
  1810. }
  1811. if (tag === "table" && isDataTable(node)) {
  1812. return false;
  1813. }
  1814. // Next check if we're inside a data table, in which case don't remove it as well.
  1815. if (this._hasAncestorTag(node, "table", -1, isDataTable)) {
  1816. return false;
  1817. }
  1818. if (this._hasAncestorTag(node, "code")) {
  1819. return false;
  1820. }
  1821. var weight = this._getClassWeight(node);
  1822. this.log("Cleaning Conditionally", node);
  1823. var contentScore = 0;
  1824. if (weight + contentScore < 0) {
  1825. return true;
  1826. }
  1827. if (this._getCharCount(node, ",") < 10) {
  1828. // If there are not very many commas, and the number of
  1829. // non-paragraph elements is more than paragraphs or other
  1830. // ominous signs, remove the element.
  1831. var p = node.getElementsByTagName("p").length;
  1832. var img = node.getElementsByTagName("img").length;
  1833. var li = node.getElementsByTagName("li").length - 100;
  1834. var input = node.getElementsByTagName("input").length;
  1835. var headingDensity = this._getTextDensity(node, ["h1", "h2", "h3", "h4", "h5", "h6"]);
  1836. var embedCount = 0;
  1837. var embeds = this._getAllNodesWithTag(node, ["object", "embed", "iframe"]);
  1838. for (var i = 0; i < embeds.length; i++) {
  1839. // If this embed has attribute that matches video regex, don't delete it.
  1840. for (var j = 0; j < embeds[i].attributes.length; j++) {
  1841. if (this.REGEXPS.videos.test(embeds[i].attributes[j].value)) {
  1842. return false;
  1843. }
  1844. }
  1845. // For embed with <object> tag, check inner HTML as well.
  1846. if (embeds[i].tagName === "object" && this.REGEXPS.videos.test(embeds[i].innerHTML)) {
  1847. return false;
  1848. }
  1849. embedCount++;
  1850. }
  1851. var linkDensity = this._getLinkDensity(node);
  1852. var contentLength = this._getInnerText(node).length;
  1853. var haveToRemove =
  1854. (img > 1 && p / img < 0.5 && !this._hasAncestorTag(node, "figure")) ||
  1855. (!isList && li > p) ||
  1856. (input > Math.floor(p/3)) ||
  1857. (!isList && headingDensity < 0.9 && contentLength < 25 && (img === 0 || img > 2) && !this._hasAncestorTag(node, "figure")) ||
  1858. (!isList && weight < 25 && linkDensity > 0.2) ||
  1859. (weight >= 25 && linkDensity > 0.5) ||
  1860. ((embedCount === 1 && contentLength < 75) || embedCount > 1);
  1861. return haveToRemove;
  1862. }
  1863. return false;
  1864. });
  1865. },
  1866. /**
  1867. * Clean out elements that match the specified conditions
  1868. *
  1869. * @param Element
  1870. * @param Function determines whether a node should be removed
  1871. * @return void
  1872. **/
  1873. _cleanMatchedNodes: function(e, filter) {
  1874. var endOfSearchMarkerNode = this._getNextNode(e, true);
  1875. var next = this._getNextNode(e);
  1876. while (next && next != endOfSearchMarkerNode) {
  1877. if (filter.call(this, next, next.className + " " + next.id)) {
  1878. next = this._removeAndGetNext(next);
  1879. } else {
  1880. next = this._getNextNode(next);
  1881. }
  1882. }
  1883. },
  1884. /**
  1885. * Clean out spurious headers from an Element.
  1886. *
  1887. * @param Element
  1888. * @return void
  1889. **/
  1890. _cleanHeaders: function(e) {
  1891. let headingNodes = this._getAllNodesWithTag(e, ["h1", "h2"]);
  1892. this._removeNodes(headingNodes, function(node) {
  1893. let shouldRemove = this._getClassWeight(node) < 0;
  1894. if (shouldRemove) {
  1895. this.log("Removing header with low class weight:", node);
  1896. }
  1897. return shouldRemove;
  1898. });
  1899. },
  1900. /**
  1901. * Check if this node is an H1 or H2 element whose content is mostly
  1902. * the same as the article title.
  1903. *
  1904. * @param Element the node to check.
  1905. * @return boolean indicating whether this is a title-like header.
  1906. */
  1907. _headerDuplicatesTitle: function(node) {
  1908. if (node.tagName != "H1" && node.tagName != "H2") {
  1909. return false;
  1910. }
  1911. var heading = this._getInnerText(node, false);
  1912. this.log("Evaluating similarity of header:", heading, this._articleTitle);
  1913. return this._textSimilarity(this._articleTitle, heading) > 0.75;
  1914. },
  1915. _flagIsActive: function(flag) {
  1916. return (this._flags & flag) > 0;
  1917. },
  1918. _removeFlag: function(flag) {
  1919. this._flags = this._flags & ~flag;
  1920. },
  1921. _isProbablyVisible: function(node) {
  1922. // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes.
  1923. return (!node.style || node.style.display != "none")
  1924. && !node.hasAttribute("hidden")
  1925. //check for "fallback-image" so that wikimedia math images are displayed
  1926. && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1));
  1927. },
  1928. /**
  1929. * Runs readability.
  1930. *
  1931. * Workflow:
  1932. * 1. Prep the document by removing script tags, css, etc.
  1933. * 2. Build readability's DOM tree.
  1934. * 3. Grab the article content from the current dom tree.
  1935. * 4. Replace the current DOM tree with the new one.
  1936. * 5. Read peacefully.
  1937. *
  1938. * @return void
  1939. **/
  1940. parse: function () {
  1941. // Avoid parsing too large documents, as per configuration option
  1942. if (this._maxElemsToParse > 0) {
  1943. var numTags = this._doc.getElementsByTagName("*").length;
  1944. if (numTags > this._maxElemsToParse) {
  1945. throw new Error("Aborting parsing document; " + numTags + " elements found");
  1946. }
  1947. }
  1948. // Unwrap image from noscript
  1949. this._unwrapNoscriptImages(this._doc);
  1950. // Extract JSON-LD metadata before removing scripts
  1951. var jsonLd = this._disableJSONLD ? {} : this._getJSONLD(this._doc);
  1952. // Remove script tags from the document.
  1953. this._removeScripts(this._doc);
  1954. this._prepDocument();
  1955. var metadata = this._getArticleMetadata(jsonLd);
  1956. this._articleTitle = metadata.title;
  1957. var articleContent = this._grabArticle();
  1958. if (!articleContent)
  1959. return null;
  1960. this.log("Grabbed: " + articleContent.innerHTML);
  1961. this._postProcessContent(articleContent);
  1962. // If we haven't found an excerpt in the article's metadata, use the article's
  1963. // first paragraph as the excerpt. This is used for displaying a preview of
  1964. // the article's content.
  1965. if (!metadata.excerpt) {
  1966. var paragraphs = articleContent.getElementsByTagName("p");
  1967. if (paragraphs.length > 0) {
  1968. metadata.excerpt = paragraphs[0].textContent.trim();
  1969. }
  1970. }
  1971. var textContent = articleContent.textContent;
  1972. return {
  1973. title: this._articleTitle,
  1974. byline: metadata.byline || this._articleByline,
  1975. dir: this._articleDir,
  1976. content: this._serializer(articleContent),
  1977. textContent: textContent,
  1978. length: textContent.length,
  1979. excerpt: metadata.excerpt,
  1980. siteName: metadata.siteName || this._articleSiteName
  1981. };
  1982. }
  1983. };
  1984. if (typeof module === "object") {
  1985. module.exports = Readability;
  1986. }