Readability.js 81 KB

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