Readability.js 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796
  1. /*
  2. * Copyright (c) 2010 Arc90 Inc
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * This code is heavily based on Arc90's readability.js (1.7.1) script
  18. * available at: http://code.google.com/p/arc90labs-readability
  19. */
  20. /**
  21. * Public constructor.
  22. * @param {HTMLDocument} doc The document to parse.
  23. * @param {Object} options The options object.
  24. */
  25. function Readability(doc, options) {
  26. // In some older versions, people passed a URI as the first argument. Cope:
  27. if (options && options.documentElement) {
  28. doc = options;
  29. options = arguments[2];
  30. } else if (!doc || !doc.documentElement) {
  31. throw new Error(
  32. "First argument to Readability constructor should be a document object."
  33. );
  34. }
  35. options = options || {};
  36. this._doc = doc;
  37. this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__;
  38. this._articleTitle = null;
  39. this._articleByline = null;
  40. this._articleDir = null;
  41. this._articleSiteName = null;
  42. this._attempts = [];
  43. this._metadata = {};
  44. // Configurable options
  45. this._debug = !!options.debug;
  46. this._maxElemsToParse =
  47. options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE;
  48. this._nbTopCandidates =
  49. options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES;
  50. this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD;
  51. this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(
  52. options.classesToPreserve || []
  53. );
  54. this._keepClasses = !!options.keepClasses;
  55. this._serializer =
  56. options.serializer ||
  57. function (el) {
  58. return el.innerHTML;
  59. };
  60. this._disableJSONLD = !!options.disableJSONLD;
  61. this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos;
  62. this._linkDensityModifier = options.linkDensityModifier || 0;
  63. // Start with all flags set
  64. this._flags =
  65. this.FLAG_STRIP_UNLIKELYS |
  66. this.FLAG_WEIGHT_CLASSES |
  67. this.FLAG_CLEAN_CONDITIONALLY;
  68. // Control whether log messages are sent to the console
  69. if (this._debug) {
  70. let logNode = function (node) {
  71. if (node.nodeType == node.TEXT_NODE) {
  72. return `${node.nodeName} ("${node.textContent}")`;
  73. }
  74. let attrPairs = Array.from(node.attributes || [], function (attr) {
  75. return `${attr.name}="${attr.value}"`;
  76. }).join(" ");
  77. return `<${node.localName} ${attrPairs}>`;
  78. };
  79. this.log = function () {
  80. if (typeof console !== "undefined") {
  81. let args = Array.from(arguments, arg => {
  82. if (arg && arg.nodeType == this.ELEMENT_NODE) {
  83. return logNode(arg);
  84. }
  85. return arg;
  86. });
  87. args.unshift("Reader: (Readability)");
  88. // eslint-disable-next-line no-console
  89. console.log(...args);
  90. } else if (typeof dump !== "undefined") {
  91. /* global dump */
  92. var msg = Array.prototype.map
  93. .call(arguments, function (x) {
  94. return x && x.nodeName ? logNode(x) : x;
  95. })
  96. .join(" ");
  97. dump("Reader: (Readability) " + msg + "\n");
  98. }
  99. };
  100. } else {
  101. this.log = function () {};
  102. }
  103. }
  104. Readability.prototype = {
  105. FLAG_STRIP_UNLIKELYS: 0x1,
  106. FLAG_WEIGHT_CLASSES: 0x2,
  107. FLAG_CLEAN_CONDITIONALLY: 0x4,
  108. // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
  109. ELEMENT_NODE: 1,
  110. TEXT_NODE: 3,
  111. // Max number of nodes supported by this parser. Default: 0 (no limit)
  112. DEFAULT_MAX_ELEMS_TO_PARSE: 0,
  113. // The number of top candidates to consider when analysing how
  114. // tight the competition is among candidates.
  115. DEFAULT_N_TOP_CANDIDATES: 5,
  116. // Element tags to score by default.
  117. DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre"
  118. .toUpperCase()
  119. .split(","),
  120. // The default number of chars an article must have in order to return a result
  121. DEFAULT_CHAR_THRESHOLD: 500,
  122. // All of the regular expressions in use within readability.
  123. // Defined up here so we don't instantiate them repeatedly in loops.
  124. REGEXPS: {
  125. // NOTE: These two regular expressions are duplicated in
  126. // Readability-readerable.js. Please keep both copies in sync.
  127. unlikelyCandidates:
  128. /-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,
  129. okMaybeItsACandidate:
  130. /and|article|body|column|content|main|mathjax|shadow/i,
  131. positive:
  132. /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i,
  133. negative:
  134. /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i,
  135. extraneous:
  136. /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i,
  137. byline: /byline|author|dateline|writtenby|p-author/i,
  138. replaceFonts: /<(\/?)font[^>]*>/gi,
  139. normalize: /\s{2,}/g,
  140. videos:
  141. /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq|bilibili|live.bilibili)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i,
  142. shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i,
  143. nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i,
  144. prevLink: /(prev|earl|old|new|<|«)/i,
  145. tokenize: /\W+/g,
  146. whitespace: /^\s*$/,
  147. hasContent: /\S$/,
  148. hashUrl: /^#.+/,
  149. srcsetUrl: /(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g,
  150. b64DataUrl: /^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i,
  151. // Commas as used in Latin, Sindhi, Chinese and various other scripts.
  152. // see: https://en.wikipedia.org/wiki/Comma#Comma_variants
  153. commas: /\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g,
  154. // See: https://schema.org/Article
  155. jsonLdArticleTypes:
  156. /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/,
  157. // used to see if a node's content matches words commonly used for ad blocks or loading indicators
  158. adWords:
  159. /^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu,
  160. loadingWords:
  161. /^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu,
  162. },
  163. UNLIKELY_ROLES: [
  164. "menu",
  165. "menubar",
  166. "complementary",
  167. "navigation",
  168. "alert",
  169. "alertdialog",
  170. "dialog",
  171. ],
  172. DIV_TO_P_ELEMS: new Set([
  173. "BLOCKQUOTE",
  174. "DL",
  175. "DIV",
  176. "IMG",
  177. "OL",
  178. "P",
  179. "PRE",
  180. "TABLE",
  181. "UL",
  182. ]),
  183. ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P", "OL", "UL"],
  184. PRESENTATIONAL_ATTRIBUTES: [
  185. "align",
  186. "background",
  187. "bgcolor",
  188. "border",
  189. "cellpadding",
  190. "cellspacing",
  191. "frame",
  192. "hspace",
  193. "rules",
  194. "style",
  195. "valign",
  196. "vspace",
  197. ],
  198. DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"],
  199. // The commented out elements qualify as phrasing content but tend to be
  200. // removed by readability when put into paragraphs, so we ignore them here.
  201. PHRASING_ELEMS: [
  202. // "CANVAS", "IFRAME", "SVG", "VIDEO",
  203. "ABBR",
  204. "AUDIO",
  205. "B",
  206. "BDO",
  207. "BR",
  208. "BUTTON",
  209. "CITE",
  210. "CODE",
  211. "DATA",
  212. "DATALIST",
  213. "DFN",
  214. "EM",
  215. "EMBED",
  216. "I",
  217. "IMG",
  218. "INPUT",
  219. "KBD",
  220. "LABEL",
  221. "MARK",
  222. "MATH",
  223. "METER",
  224. "NOSCRIPT",
  225. "OBJECT",
  226. "OUTPUT",
  227. "PROGRESS",
  228. "Q",
  229. "RUBY",
  230. "SAMP",
  231. "SCRIPT",
  232. "SELECT",
  233. "SMALL",
  234. "SPAN",
  235. "STRONG",
  236. "SUB",
  237. "SUP",
  238. "TEXTAREA",
  239. "TIME",
  240. "VAR",
  241. "WBR",
  242. ],
  243. // These are the classes that readability sets itself.
  244. CLASSES_TO_PRESERVE: ["page"],
  245. // These are the list of HTML entities that need to be escaped.
  246. HTML_ESCAPE_MAP: {
  247. lt: "<",
  248. gt: ">",
  249. amp: "&",
  250. quot: '"',
  251. apos: "'",
  252. },
  253. /**
  254. * Run any post-process modifications to article content as necessary.
  255. *
  256. * @param Element
  257. * @return void
  258. **/
  259. _postProcessContent(articleContent) {
  260. // Readability cannot open relative uris so we convert them to absolute uris.
  261. this._fixRelativeUris(articleContent);
  262. this._simplifyNestedElements(articleContent);
  263. if (!this._keepClasses) {
  264. // Remove classes.
  265. this._cleanClasses(articleContent);
  266. }
  267. },
  268. /**
  269. * Iterates over a NodeList, calls `filterFn` for each node and removes node
  270. * if function returned `true`.
  271. *
  272. * If function is not passed, removes all the nodes in node list.
  273. *
  274. * @param NodeList nodeList The nodes to operate on
  275. * @param Function filterFn the function to use as a filter
  276. * @return void
  277. */
  278. _removeNodes(nodeList, filterFn) {
  279. // Avoid ever operating on live node lists.
  280. if (this._docJSDOMParser && nodeList._isLiveNodeList) {
  281. throw new Error("Do not pass live node lists to _removeNodes");
  282. }
  283. for (var i = nodeList.length - 1; i >= 0; i--) {
  284. var node = nodeList[i];
  285. var parentNode = node.parentNode;
  286. if (parentNode) {
  287. if (!filterFn || filterFn.call(this, node, i, nodeList)) {
  288. parentNode.removeChild(node);
  289. }
  290. }
  291. }
  292. },
  293. /**
  294. * Iterates over a NodeList, and calls _setNodeTag for each node.
  295. *
  296. * @param NodeList nodeList The nodes to operate on
  297. * @param String newTagName the new tag name to use
  298. * @return void
  299. */
  300. _replaceNodeTags(nodeList, newTagName) {
  301. // Avoid ever operating on live node lists.
  302. if (this._docJSDOMParser && nodeList._isLiveNodeList) {
  303. throw new Error("Do not pass live node lists to _replaceNodeTags");
  304. }
  305. for (const node of nodeList) {
  306. this._setNodeTag(node, newTagName);
  307. }
  308. },
  309. /**
  310. * Iterate over a NodeList, which doesn't natively fully implement the Array
  311. * interface.
  312. *
  313. * For convenience, the current object context is applied to the provided
  314. * iterate function.
  315. *
  316. * @param NodeList nodeList The NodeList.
  317. * @param Function fn The iterate function.
  318. * @return void
  319. */
  320. _forEachNode(nodeList, fn) {
  321. Array.prototype.forEach.call(nodeList, fn, this);
  322. },
  323. /**
  324. * Iterate over a NodeList, and return the first node that passes
  325. * the supplied test function
  326. *
  327. * For convenience, the current object context is applied to the provided
  328. * test function.
  329. *
  330. * @param NodeList nodeList The NodeList.
  331. * @param Function fn The test function.
  332. * @return void
  333. */
  334. _findNode(nodeList, fn) {
  335. return Array.prototype.find.call(nodeList, fn, this);
  336. },
  337. /**
  338. * Iterate over a NodeList, return true if any of the provided iterate
  339. * function calls returns true, false otherwise.
  340. *
  341. * For convenience, the current object context is applied to the
  342. * provided iterate function.
  343. *
  344. * @param NodeList nodeList The NodeList.
  345. * @param Function fn The iterate function.
  346. * @return Boolean
  347. */
  348. _someNode(nodeList, fn) {
  349. return Array.prototype.some.call(nodeList, fn, this);
  350. },
  351. /**
  352. * Iterate over a NodeList, return true if all of the provided iterate
  353. * function calls return true, false otherwise.
  354. *
  355. * For convenience, the current object context is applied to the
  356. * provided iterate function.
  357. *
  358. * @param NodeList nodeList The NodeList.
  359. * @param Function fn The iterate function.
  360. * @return Boolean
  361. */
  362. _everyNode(nodeList, fn) {
  363. return Array.prototype.every.call(nodeList, fn, this);
  364. },
  365. _getAllNodesWithTag(node, tagNames) {
  366. if (node.querySelectorAll) {
  367. return node.querySelectorAll(tagNames.join(","));
  368. }
  369. return [].concat.apply(
  370. [],
  371. tagNames.map(function (tag) {
  372. var collection = node.getElementsByTagName(tag);
  373. return Array.isArray(collection) ? collection : Array.from(collection);
  374. })
  375. );
  376. },
  377. /**
  378. * Removes the class="" attribute from every element in the given
  379. * subtree, except those that match CLASSES_TO_PRESERVE and
  380. * the classesToPreserve array from the options object.
  381. *
  382. * @param Element
  383. * @return void
  384. */
  385. _cleanClasses(node) {
  386. var classesToPreserve = this._classesToPreserve;
  387. var className = (node.getAttribute("class") || "")
  388. .split(/\s+/)
  389. .filter(cls => classesToPreserve.includes(cls))
  390. .join(" ");
  391. if (className) {
  392. node.setAttribute("class", className);
  393. } else {
  394. node.removeAttribute("class");
  395. }
  396. for (node = node.firstElementChild; node; node = node.nextElementSibling) {
  397. this._cleanClasses(node);
  398. }
  399. },
  400. /**
  401. * Tests whether a string is a URL or not.
  402. *
  403. * @param {string} str The string to test
  404. * @return {boolean} true if str is a URL, false if not
  405. */
  406. _isUrl(str) {
  407. try {
  408. new URL(str);
  409. return true;
  410. } catch {
  411. return false;
  412. }
  413. },
  414. /**
  415. * Converts each <a> and <img> uri in the given element to an absolute URI,
  416. * ignoring #ref URIs.
  417. *
  418. * @param Element
  419. * @return void
  420. */
  421. _fixRelativeUris(articleContent) {
  422. var baseURI = this._doc.baseURI;
  423. var documentURI = this._doc.documentURI;
  424. function toAbsoluteURI(uri) {
  425. // Leave hash links alone if the base URI matches the document URI:
  426. if (baseURI == documentURI && uri.charAt(0) == "#") {
  427. return uri;
  428. }
  429. // Otherwise, resolve against base URI:
  430. try {
  431. return new URL(uri, baseURI).href;
  432. } catch (ex) {
  433. // Something went wrong, just return the original:
  434. }
  435. return uri;
  436. }
  437. var links = this._getAllNodesWithTag(articleContent, ["a"]);
  438. this._forEachNode(links, function (link) {
  439. var href = link.getAttribute("href");
  440. if (href) {
  441. // Remove links with javascript: URIs, since
  442. // they won't work after scripts have been removed from the page.
  443. if (href.indexOf("javascript:") === 0) {
  444. // if the link only contains simple text content, it can be converted to a text node
  445. if (
  446. link.childNodes.length === 1 &&
  447. link.childNodes[0].nodeType === this.TEXT_NODE
  448. ) {
  449. var text = this._doc.createTextNode(link.textContent);
  450. link.parentNode.replaceChild(text, link);
  451. } else {
  452. // if the link has multiple children, they should all be preserved
  453. var container = this._doc.createElement("span");
  454. while (link.firstChild) {
  455. container.appendChild(link.firstChild);
  456. }
  457. link.parentNode.replaceChild(container, link);
  458. }
  459. } else {
  460. link.setAttribute("href", toAbsoluteURI(href));
  461. }
  462. }
  463. });
  464. var medias = this._getAllNodesWithTag(articleContent, [
  465. "img",
  466. "picture",
  467. "figure",
  468. "video",
  469. "audio",
  470. "source",
  471. ]);
  472. this._forEachNode(medias, function (media) {
  473. var src = media.getAttribute("src");
  474. var poster = media.getAttribute("poster");
  475. var srcset = media.getAttribute("srcset");
  476. if (src) {
  477. media.setAttribute("src", toAbsoluteURI(src));
  478. }
  479. if (poster) {
  480. media.setAttribute("poster", toAbsoluteURI(poster));
  481. }
  482. if (srcset) {
  483. var newSrcset = srcset.replace(
  484. this.REGEXPS.srcsetUrl,
  485. function (_, p1, p2, p3) {
  486. return toAbsoluteURI(p1) + (p2 || "") + p3;
  487. }
  488. );
  489. media.setAttribute("srcset", newSrcset);
  490. }
  491. });
  492. },
  493. _simplifyNestedElements(articleContent) {
  494. var node = articleContent;
  495. while (node) {
  496. if (
  497. node.parentNode &&
  498. ["DIV", "SECTION"].includes(node.tagName) &&
  499. !(node.id && node.id.startsWith("readability"))
  500. ) {
  501. if (this._isElementWithoutContent(node)) {
  502. node = this._removeAndGetNext(node);
  503. continue;
  504. } else if (
  505. this._hasSingleTagInsideElement(node, "DIV") ||
  506. this._hasSingleTagInsideElement(node, "SECTION")
  507. ) {
  508. var child = node.children[0];
  509. for (var i = 0; i < node.attributes.length; i++) {
  510. child.setAttributeNode(node.attributes[i].cloneNode());
  511. }
  512. node.parentNode.replaceChild(child, node);
  513. node = child;
  514. continue;
  515. }
  516. }
  517. node = this._getNextNode(node);
  518. }
  519. },
  520. /**
  521. * Get the article title as an H1.
  522. *
  523. * @return string
  524. **/
  525. _getArticleTitle() {
  526. var doc = this._doc;
  527. var curTitle = "";
  528. var origTitle = "";
  529. try {
  530. curTitle = origTitle = doc.title.trim();
  531. // If they had an element with id "title" in their HTML
  532. if (typeof curTitle !== "string") {
  533. curTitle = origTitle = this._getInnerText(
  534. doc.getElementsByTagName("title")[0]
  535. );
  536. }
  537. } catch (e) {
  538. /* ignore exceptions setting the title. */
  539. }
  540. var titleHadHierarchicalSeparators = false;
  541. function wordCount(str) {
  542. return str.split(/\s+/).length;
  543. }
  544. // If there's a separator in the title, first remove the final part
  545. const titleSeparators = /\|\-–—\\\/>»/.source;
  546. if (new RegExp(`\\s[${titleSeparators}]\\s`).test(curTitle)) {
  547. titleHadHierarchicalSeparators = /\s[\\\/>»]\s/.test(curTitle);
  548. let allSeparators = Array.from(
  549. origTitle.matchAll(new RegExp(`\\s[${titleSeparators}]\\s`, "gi"))
  550. );
  551. curTitle = origTitle.substring(0, allSeparators.pop().index);
  552. // If the resulting title is too short, remove the first part instead:
  553. if (wordCount(curTitle) < 3) {
  554. curTitle = origTitle.replace(
  555. new RegExp(`^[^${titleSeparators}]*[${titleSeparators}]`, "gi"),
  556. ""
  557. );
  558. }
  559. } else if (curTitle.includes(": ")) {
  560. // Check if we have an heading containing this exact string, so we
  561. // could assume it's the full title.
  562. var headings = this._getAllNodesWithTag(doc, ["h1", "h2"]);
  563. var trimmedTitle = curTitle.trim();
  564. var match = this._someNode(headings, function (heading) {
  565. return heading.textContent.trim() === trimmedTitle;
  566. });
  567. // If we don't, let's extract the title out of the original title string.
  568. if (!match) {
  569. curTitle = origTitle.substring(origTitle.lastIndexOf(":") + 1);
  570. // If the title is now too short, try the first colon instead:
  571. if (wordCount(curTitle) < 3) {
  572. curTitle = origTitle.substring(origTitle.indexOf(":") + 1);
  573. // But if we have too many words before the colon there's something weird
  574. // with the titles and the H tags so let's just use the original title instead
  575. } else if (wordCount(origTitle.substr(0, origTitle.indexOf(":"))) > 5) {
  576. curTitle = origTitle;
  577. }
  578. }
  579. } else if (curTitle.length > 150 || curTitle.length < 15) {
  580. var hOnes = doc.getElementsByTagName("h1");
  581. if (hOnes.length === 1) {
  582. curTitle = this._getInnerText(hOnes[0]);
  583. }
  584. }
  585. curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " ");
  586. // If we now have 4 words or fewer as our title, and either no
  587. // 'hierarchical' separators (\, /, > or ») were found in the original
  588. // title or we decreased the number of words by more than 1 word, use
  589. // the original title.
  590. var curTitleWordCount = wordCount(curTitle);
  591. if (
  592. curTitleWordCount <= 4 &&
  593. (!titleHadHierarchicalSeparators ||
  594. curTitleWordCount !=
  595. wordCount(
  596. origTitle.replace(new RegExp(`\\s[${titleSeparators}]\\s`, "g"), "")
  597. ) -
  598. 1)
  599. ) {
  600. curTitle = origTitle;
  601. }
  602. return curTitle;
  603. },
  604. /**
  605. * Prepare the HTML document for readability to scrape it.
  606. * This includes things like stripping javascript, CSS, and handling terrible markup.
  607. *
  608. * @return void
  609. **/
  610. _prepDocument() {
  611. var doc = this._doc;
  612. // Remove all style tags in head
  613. this._removeNodes(this._getAllNodesWithTag(doc, ["style"]));
  614. if (doc.body) {
  615. this._replaceBrs(doc.body);
  616. }
  617. this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN");
  618. },
  619. /**
  620. * Finds the next node, starting from the given node, and ignoring
  621. * whitespace in between. If the given node is an element, the same node is
  622. * returned.
  623. */
  624. _nextNode(node) {
  625. var next = node;
  626. while (
  627. next &&
  628. next.nodeType != this.ELEMENT_NODE &&
  629. this.REGEXPS.whitespace.test(next.textContent)
  630. ) {
  631. next = next.nextSibling;
  632. }
  633. return next;
  634. },
  635. /**
  636. * Replaces 2 or more successive <br> elements with a single <p>.
  637. * Whitespace between <br> elements are ignored. For example:
  638. * <div>foo<br>bar<br> <br><br>abc</div>
  639. * will become:
  640. * <div>foo<br>bar<p>abc</p></div>
  641. */
  642. _replaceBrs(elem) {
  643. this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function (br) {
  644. var next = br.nextSibling;
  645. // Whether 2 or more <br> elements have been found and replaced with a
  646. // <p> block.
  647. var replaced = false;
  648. // If we find a <br> chain, remove the <br>s until we hit another node
  649. // or non-whitespace. This leaves behind the first <br> in the chain
  650. // (which will be replaced with a <p> later).
  651. while ((next = this._nextNode(next)) && next.tagName == "BR") {
  652. replaced = true;
  653. var brSibling = next.nextSibling;
  654. next.remove();
  655. next = brSibling;
  656. }
  657. // If we removed a <br> chain, replace the remaining <br> with a <p>. Add
  658. // all sibling nodes as children of the <p> until we hit another <br>
  659. // chain.
  660. if (replaced) {
  661. var p = this._doc.createElement("p");
  662. br.parentNode.replaceChild(p, br);
  663. next = p.nextSibling;
  664. while (next) {
  665. // If we've hit another <br><br>, we're done adding children to this <p>.
  666. if (next.tagName == "BR") {
  667. var nextElem = this._nextNode(next.nextSibling);
  668. if (nextElem && nextElem.tagName == "BR") {
  669. break;
  670. }
  671. }
  672. if (!this._isPhrasingContent(next)) {
  673. break;
  674. }
  675. // Otherwise, make this node a child of the new <p>.
  676. var sibling = next.nextSibling;
  677. p.appendChild(next);
  678. next = sibling;
  679. }
  680. while (p.lastChild && this._isWhitespace(p.lastChild)) {
  681. p.lastChild.remove();
  682. }
  683. if (p.parentNode.tagName === "P") {
  684. this._setNodeTag(p.parentNode, "DIV");
  685. }
  686. }
  687. });
  688. },
  689. _setNodeTag(node, tag) {
  690. this.log("_setNodeTag", node, tag);
  691. if (this._docJSDOMParser) {
  692. node.localName = tag.toLowerCase();
  693. node.tagName = tag.toUpperCase();
  694. return node;
  695. }
  696. var replacement = node.ownerDocument.createElement(tag);
  697. while (node.firstChild) {
  698. replacement.appendChild(node.firstChild);
  699. }
  700. node.parentNode.replaceChild(replacement, node);
  701. if (node.readability) {
  702. replacement.readability = node.readability;
  703. }
  704. for (var i = 0; i < node.attributes.length; i++) {
  705. replacement.setAttributeNode(node.attributes[i].cloneNode());
  706. }
  707. return replacement;
  708. },
  709. /**
  710. * Prepare the article node for display. Clean out any inline styles,
  711. * iframes, forms, strip extraneous <p> tags, etc.
  712. *
  713. * @param Element
  714. * @return void
  715. **/
  716. _prepArticle(articleContent) {
  717. this._cleanStyles(articleContent);
  718. // Check for data tables before we continue, to avoid removing items in
  719. // those tables, which will often be isolated even though they're
  720. // visually linked to other content-ful elements (text, images, etc.).
  721. this._markDataTables(articleContent);
  722. this._fixLazyImages(articleContent);
  723. // Clean out junk from the article content
  724. this._cleanConditionally(articleContent, "form");
  725. this._cleanConditionally(articleContent, "fieldset");
  726. this._clean(articleContent, "object");
  727. this._clean(articleContent, "embed");
  728. this._clean(articleContent, "footer");
  729. this._clean(articleContent, "link");
  730. this._clean(articleContent, "aside");
  731. // Clean out elements with little content that have "share" in their id/class combinations from final top candidates,
  732. // which means we don't remove the top candidates even they have "share".
  733. var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD;
  734. this._forEachNode(articleContent.children, function (topCandidate) {
  735. this._cleanMatchedNodes(topCandidate, function (node, matchString) {
  736. return (
  737. this.REGEXPS.shareElements.test(matchString) &&
  738. node.textContent.length < shareElementThreshold
  739. );
  740. });
  741. });
  742. this._clean(articleContent, "iframe");
  743. this._clean(articleContent, "input");
  744. this._clean(articleContent, "textarea");
  745. this._clean(articleContent, "select");
  746. this._clean(articleContent, "button");
  747. this._cleanHeaders(articleContent);
  748. // Do these last as the previous stuff may have removed junk
  749. // that will affect these
  750. this._cleanConditionally(articleContent, "table");
  751. this._cleanConditionally(articleContent, "ul");
  752. this._cleanConditionally(articleContent, "div");
  753. // replace H1 with H2 as H1 should be only title that is displayed separately
  754. this._replaceNodeTags(
  755. this._getAllNodesWithTag(articleContent, ["h1"]),
  756. "h2"
  757. );
  758. // Remove extra paragraphs
  759. this._removeNodes(
  760. this._getAllNodesWithTag(articleContent, ["p"]),
  761. function (paragraph) {
  762. // At this point, nasty iframes have been removed; only embedded video
  763. // ones remain.
  764. var contentElementCount = this._getAllNodesWithTag(paragraph, [
  765. "img",
  766. "embed",
  767. "object",
  768. "iframe",
  769. ]).length;
  770. return (
  771. contentElementCount === 0 && !this._getInnerText(paragraph, false)
  772. );
  773. }
  774. );
  775. this._forEachNode(
  776. this._getAllNodesWithTag(articleContent, ["br"]),
  777. function (br) {
  778. var next = this._nextNode(br.nextSibling);
  779. if (next && next.tagName == "P") {
  780. br.remove();
  781. }
  782. }
  783. );
  784. // Remove single-cell tables
  785. this._forEachNode(
  786. this._getAllNodesWithTag(articleContent, ["table"]),
  787. function (table) {
  788. var tbody = this._hasSingleTagInsideElement(table, "TBODY")
  789. ? table.firstElementChild
  790. : table;
  791. if (this._hasSingleTagInsideElement(tbody, "TR")) {
  792. var row = tbody.firstElementChild;
  793. if (this._hasSingleTagInsideElement(row, "TD")) {
  794. var cell = row.firstElementChild;
  795. cell = this._setNodeTag(
  796. cell,
  797. this._everyNode(cell.childNodes, this._isPhrasingContent)
  798. ? "P"
  799. : "DIV"
  800. );
  801. table.parentNode.replaceChild(cell, table);
  802. }
  803. }
  804. }
  805. );
  806. },
  807. /**
  808. * Initialize a node with the readability object. Also checks the
  809. * className/id for special names to add to its score.
  810. *
  811. * @param Element
  812. * @return void
  813. **/
  814. _initializeNode(node) {
  815. node.readability = { contentScore: 0 };
  816. switch (node.tagName) {
  817. case "DIV":
  818. node.readability.contentScore += 5;
  819. break;
  820. case "PRE":
  821. case "TD":
  822. case "BLOCKQUOTE":
  823. node.readability.contentScore += 3;
  824. break;
  825. case "ADDRESS":
  826. case "OL":
  827. case "UL":
  828. case "DL":
  829. case "DD":
  830. case "DT":
  831. case "LI":
  832. case "FORM":
  833. node.readability.contentScore -= 3;
  834. break;
  835. case "H1":
  836. case "H2":
  837. case "H3":
  838. case "H4":
  839. case "H5":
  840. case "H6":
  841. case "TH":
  842. node.readability.contentScore -= 5;
  843. break;
  844. }
  845. node.readability.contentScore += this._getClassWeight(node);
  846. },
  847. _removeAndGetNext(node) {
  848. var nextNode = this._getNextNode(node, true);
  849. node.remove();
  850. return nextNode;
  851. },
  852. /**
  853. * Traverse the DOM from node to node, starting at the node passed in.
  854. * Pass true for the second parameter to indicate this node itself
  855. * (and its kids) are going away, and we want the next node over.
  856. *
  857. * Calling this in a loop will traverse the DOM depth-first.
  858. *
  859. * @param {Element} node
  860. * @param {boolean} ignoreSelfAndKids
  861. * @return {Element}
  862. */
  863. _getNextNode(node, ignoreSelfAndKids) {
  864. // First check for kids if those aren't being ignored
  865. if (!ignoreSelfAndKids && node.firstElementChild) {
  866. return node.firstElementChild;
  867. }
  868. // Then for siblings...
  869. if (node.nextElementSibling) {
  870. return node.nextElementSibling;
  871. }
  872. // And finally, move up the parent chain *and* find a sibling
  873. // (because this is depth-first traversal, we will have already
  874. // seen the parent nodes themselves).
  875. do {
  876. node = node.parentNode;
  877. } while (node && !node.nextElementSibling);
  878. return node && node.nextElementSibling;
  879. },
  880. // compares second text to first one
  881. // 1 = same text, 0 = completely different text
  882. // works the way that it splits both texts into words and then finds words that are unique in second text
  883. // the result is given by the lower length of unique parts
  884. _textSimilarity(textA, textB) {
  885. var tokensA = textA
  886. .toLowerCase()
  887. .split(this.REGEXPS.tokenize)
  888. .filter(Boolean);
  889. var tokensB = textB
  890. .toLowerCase()
  891. .split(this.REGEXPS.tokenize)
  892. .filter(Boolean);
  893. if (!tokensA.length || !tokensB.length) {
  894. return 0;
  895. }
  896. var uniqTokensB = tokensB.filter(token => !tokensA.includes(token));
  897. var distanceB = uniqTokensB.join(" ").length / tokensB.join(" ").length;
  898. return 1 - distanceB;
  899. },
  900. /**
  901. * Checks whether an element node contains a valid byline
  902. *
  903. * @param node {Element}
  904. * @param matchString {string}
  905. * @return boolean
  906. */
  907. _isValidByline(node, matchString) {
  908. var rel = node.getAttribute("rel");
  909. var itemprop = node.getAttribute("itemprop");
  910. var bylineLength = node.textContent.trim().length;
  911. return (
  912. (rel === "author" ||
  913. (itemprop && itemprop.includes("author")) ||
  914. this.REGEXPS.byline.test(matchString)) &&
  915. !!bylineLength &&
  916. bylineLength < 100
  917. );
  918. },
  919. _getNodeAncestors(node, maxDepth) {
  920. maxDepth = maxDepth || 0;
  921. var i = 0,
  922. ancestors = [];
  923. while (node.parentNode) {
  924. ancestors.push(node.parentNode);
  925. if (maxDepth && ++i === maxDepth) {
  926. break;
  927. }
  928. node = node.parentNode;
  929. }
  930. return ancestors;
  931. },
  932. /***
  933. * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
  934. * most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
  935. *
  936. * @param page a document to run upon. Needs to be a full document, complete with body.
  937. * @return Element
  938. **/
  939. /* eslint-disable-next-line complexity */
  940. _grabArticle(page) {
  941. this.log("**** grabArticle ****");
  942. var doc = this._doc;
  943. var isPaging = page !== null;
  944. page = page ? page : this._doc.body;
  945. // We can't grab an article if we don't have a page!
  946. if (!page) {
  947. this.log("No body found in document. Abort.");
  948. return null;
  949. }
  950. var pageCacheHtml = page.innerHTML;
  951. while (true) {
  952. this.log("Starting grabArticle loop");
  953. var stripUnlikelyCandidates = this._flagIsActive(
  954. this.FLAG_STRIP_UNLIKELYS
  955. );
  956. // First, node prepping. Trash nodes that look cruddy (like ones with the
  957. // class name "comment", etc), and turn divs into P tags where they have been
  958. // used inappropriately (as in, where they contain no other block level elements.)
  959. var elementsToScore = [];
  960. var node = this._doc.documentElement;
  961. let shouldRemoveTitleHeader = true;
  962. while (node) {
  963. if (node.tagName === "HTML") {
  964. this._articleLang = node.getAttribute("lang");
  965. }
  966. var matchString = node.className + " " + node.id;
  967. if (!this._isProbablyVisible(node)) {
  968. this.log("Removing hidden node - " + matchString);
  969. node = this._removeAndGetNext(node);
  970. continue;
  971. }
  972. // User is not able to see elements applied with both "aria-modal = true" and "role = dialog"
  973. if (
  974. node.getAttribute("aria-modal") == "true" &&
  975. node.getAttribute("role") == "dialog"
  976. ) {
  977. node = this._removeAndGetNext(node);
  978. continue;
  979. }
  980. // If we don't have a byline yet check to see if this node is a byline; if it is store the byline and remove the node.
  981. if (
  982. !this._articleByline &&
  983. !this._metadata.byline &&
  984. this._isValidByline(node, matchString)
  985. ) {
  986. // Find child node matching [itemprop="name"] and use that if it exists for a more accurate author name byline
  987. var endOfSearchMarkerNode = this._getNextNode(node, true);
  988. var next = this._getNextNode(node);
  989. var itemPropNameNode = null;
  990. while (next && next != endOfSearchMarkerNode) {
  991. var itemprop = next.getAttribute("itemprop");
  992. if (itemprop && itemprop.includes("name")) {
  993. itemPropNameNode = next;
  994. break;
  995. } else {
  996. next = this._getNextNode(next);
  997. }
  998. }
  999. this._articleByline = (itemPropNameNode ?? node).textContent.trim();
  1000. node = this._removeAndGetNext(node);
  1001. continue;
  1002. }
  1003. if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) {
  1004. this.log(
  1005. "Removing header: ",
  1006. node.textContent.trim(),
  1007. this._articleTitle.trim()
  1008. );
  1009. shouldRemoveTitleHeader = false;
  1010. node = this._removeAndGetNext(node);
  1011. continue;
  1012. }
  1013. // Remove unlikely candidates
  1014. if (stripUnlikelyCandidates) {
  1015. if (
  1016. this.REGEXPS.unlikelyCandidates.test(matchString) &&
  1017. !this.REGEXPS.okMaybeItsACandidate.test(matchString) &&
  1018. !this._hasAncestorTag(node, "table") &&
  1019. !this._hasAncestorTag(node, "code") &&
  1020. node.tagName !== "BODY" &&
  1021. node.tagName !== "A"
  1022. ) {
  1023. this.log("Removing unlikely candidate - " + matchString);
  1024. node = this._removeAndGetNext(node);
  1025. continue;
  1026. }
  1027. if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) {
  1028. this.log(
  1029. "Removing content with role " +
  1030. node.getAttribute("role") +
  1031. " - " +
  1032. matchString
  1033. );
  1034. node = this._removeAndGetNext(node);
  1035. continue;
  1036. }
  1037. }
  1038. // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
  1039. if (
  1040. (node.tagName === "DIV" ||
  1041. node.tagName === "SECTION" ||
  1042. node.tagName === "HEADER" ||
  1043. node.tagName === "H1" ||
  1044. node.tagName === "H2" ||
  1045. node.tagName === "H3" ||
  1046. node.tagName === "H4" ||
  1047. node.tagName === "H5" ||
  1048. node.tagName === "H6") &&
  1049. this._isElementWithoutContent(node)
  1050. ) {
  1051. node = this._removeAndGetNext(node);
  1052. continue;
  1053. }
  1054. if (this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)) {
  1055. elementsToScore.push(node);
  1056. }
  1057. // Turn all divs that don't have children block level elements into p's
  1058. if (node.tagName === "DIV") {
  1059. // Put phrasing content into paragraphs.
  1060. var p = null;
  1061. var childNode = node.firstChild;
  1062. while (childNode) {
  1063. var nextSibling = childNode.nextSibling;
  1064. if (this._isPhrasingContent(childNode)) {
  1065. if (p !== null) {
  1066. p.appendChild(childNode);
  1067. } else if (!this._isWhitespace(childNode)) {
  1068. p = doc.createElement("p");
  1069. node.replaceChild(p, childNode);
  1070. p.appendChild(childNode);
  1071. }
  1072. } else if (p !== null) {
  1073. while (p.lastChild && this._isWhitespace(p.lastChild)) {
  1074. p.lastChild.remove();
  1075. }
  1076. p = null;
  1077. }
  1078. childNode = nextSibling;
  1079. }
  1080. // Sites like http://mobile.slate.com encloses each paragraph with a DIV
  1081. // element. DIVs with only a P element inside and no text content can be
  1082. // safely converted into plain P elements to avoid confusing the scoring
  1083. // algorithm with DIVs with are, in practice, paragraphs.
  1084. if (
  1085. this._hasSingleTagInsideElement(node, "P") &&
  1086. this._getLinkDensity(node) < 0.25
  1087. ) {
  1088. var newNode = node.children[0];
  1089. node.parentNode.replaceChild(newNode, node);
  1090. node = newNode;
  1091. elementsToScore.push(node);
  1092. } else if (!this._hasChildBlockElement(node)) {
  1093. node = this._setNodeTag(node, "P");
  1094. elementsToScore.push(node);
  1095. }
  1096. }
  1097. node = this._getNextNode(node);
  1098. }
  1099. /**
  1100. * Loop through all paragraphs, and assign a score to them based on how content-y they look.
  1101. * Then add their score to their parent node.
  1102. *
  1103. * A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
  1104. **/
  1105. var candidates = [];
  1106. this._forEachNode(elementsToScore, function (elementToScore) {
  1107. if (
  1108. !elementToScore.parentNode ||
  1109. typeof elementToScore.parentNode.tagName === "undefined"
  1110. ) {
  1111. return;
  1112. }
  1113. // If this paragraph is less than 25 characters, don't even count it.
  1114. var innerText = this._getInnerText(elementToScore);
  1115. if (innerText.length < 25) {
  1116. return;
  1117. }
  1118. // Exclude nodes with no ancestor.
  1119. var ancestors = this._getNodeAncestors(elementToScore, 5);
  1120. if (ancestors.length === 0) {
  1121. return;
  1122. }
  1123. var contentScore = 0;
  1124. // Add a point for the paragraph itself as a base.
  1125. contentScore += 1;
  1126. // Add points for any commas within this paragraph.
  1127. contentScore += innerText.split(this.REGEXPS.commas).length;
  1128. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  1129. contentScore += Math.min(Math.floor(innerText.length / 100), 3);
  1130. // Initialize and score ancestors.
  1131. this._forEachNode(ancestors, function (ancestor, level) {
  1132. if (
  1133. !ancestor.tagName ||
  1134. !ancestor.parentNode ||
  1135. typeof ancestor.parentNode.tagName === "undefined"
  1136. ) {
  1137. return;
  1138. }
  1139. if (typeof ancestor.readability === "undefined") {
  1140. this._initializeNode(ancestor);
  1141. candidates.push(ancestor);
  1142. }
  1143. // Node score divider:
  1144. // - parent: 1 (no division)
  1145. // - grandparent: 2
  1146. // - great grandparent+: ancestor level * 3
  1147. if (level === 0) {
  1148. var scoreDivider = 1;
  1149. } else if (level === 1) {
  1150. scoreDivider = 2;
  1151. } else {
  1152. scoreDivider = level * 3;
  1153. }
  1154. ancestor.readability.contentScore += contentScore / scoreDivider;
  1155. });
  1156. });
  1157. // After we've calculated scores, loop through all of the possible
  1158. // candidate nodes we found and find the one with the highest score.
  1159. var topCandidates = [];
  1160. for (var c = 0, cl = candidates.length; c < cl; c += 1) {
  1161. var candidate = candidates[c];
  1162. // Scale the final candidates score based on link density. Good content
  1163. // should have a relatively small link density (5% or less) and be mostly
  1164. // unaffected by this operation.
  1165. var candidateScore =
  1166. candidate.readability.contentScore *
  1167. (1 - this._getLinkDensity(candidate));
  1168. candidate.readability.contentScore = candidateScore;
  1169. this.log("Candidate:", candidate, "with score " + candidateScore);
  1170. for (var t = 0; t < this._nbTopCandidates; t++) {
  1171. var aTopCandidate = topCandidates[t];
  1172. if (
  1173. !aTopCandidate ||
  1174. candidateScore > aTopCandidate.readability.contentScore
  1175. ) {
  1176. topCandidates.splice(t, 0, candidate);
  1177. if (topCandidates.length > this._nbTopCandidates) {
  1178. topCandidates.pop();
  1179. }
  1180. break;
  1181. }
  1182. }
  1183. }
  1184. var topCandidate = topCandidates[0] || null;
  1185. var neededToCreateTopCandidate = false;
  1186. var parentOfTopCandidate;
  1187. // If we still have no top candidate, just use the body as a last resort.
  1188. // We also have to copy the body node so it is something we can modify.
  1189. if (topCandidate === null || topCandidate.tagName === "BODY") {
  1190. // Move all of the page's children into topCandidate
  1191. topCandidate = doc.createElement("DIV");
  1192. neededToCreateTopCandidate = true;
  1193. // Move everything (not just elements, also text nodes etc.) into the container
  1194. // so we even include text directly in the body:
  1195. while (page.firstChild) {
  1196. this.log("Moving child out:", page.firstChild);
  1197. topCandidate.appendChild(page.firstChild);
  1198. }
  1199. page.appendChild(topCandidate);
  1200. this._initializeNode(topCandidate);
  1201. } else if (topCandidate) {
  1202. // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
  1203. // and whose scores are quite closed with current `topCandidate` node.
  1204. var alternativeCandidateAncestors = [];
  1205. for (var i = 1; i < topCandidates.length; i++) {
  1206. if (
  1207. topCandidates[i].readability.contentScore /
  1208. topCandidate.readability.contentScore >=
  1209. 0.75
  1210. ) {
  1211. alternativeCandidateAncestors.push(
  1212. this._getNodeAncestors(topCandidates[i])
  1213. );
  1214. }
  1215. }
  1216. var MINIMUM_TOPCANDIDATES = 3;
  1217. if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) {
  1218. parentOfTopCandidate = topCandidate.parentNode;
  1219. while (parentOfTopCandidate.tagName !== "BODY") {
  1220. var listsContainingThisAncestor = 0;
  1221. for (
  1222. var ancestorIndex = 0;
  1223. ancestorIndex < alternativeCandidateAncestors.length &&
  1224. listsContainingThisAncestor < MINIMUM_TOPCANDIDATES;
  1225. ancestorIndex++
  1226. ) {
  1227. listsContainingThisAncestor += Number(
  1228. alternativeCandidateAncestors[ancestorIndex].includes(
  1229. parentOfTopCandidate
  1230. )
  1231. );
  1232. }
  1233. if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) {
  1234. topCandidate = parentOfTopCandidate;
  1235. break;
  1236. }
  1237. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  1238. }
  1239. }
  1240. if (!topCandidate.readability) {
  1241. this._initializeNode(topCandidate);
  1242. }
  1243. // Because of our bonus system, parents of candidates might have scores
  1244. // themselves. They get half of the node. There won't be nodes with higher
  1245. // scores than our topCandidate, but if we see the score going *up* in the first
  1246. // few steps up the tree, that's a decent sign that there might be more content
  1247. // lurking in other places that we want to unify in. The sibling stuff
  1248. // below does some of that - but only if we've looked high enough up the DOM
  1249. // tree.
  1250. parentOfTopCandidate = topCandidate.parentNode;
  1251. var lastScore = topCandidate.readability.contentScore;
  1252. // The scores shouldn't get too low.
  1253. var scoreThreshold = lastScore / 3;
  1254. while (parentOfTopCandidate.tagName !== "BODY") {
  1255. if (!parentOfTopCandidate.readability) {
  1256. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  1257. continue;
  1258. }
  1259. var parentScore = parentOfTopCandidate.readability.contentScore;
  1260. if (parentScore < scoreThreshold) {
  1261. break;
  1262. }
  1263. if (parentScore > lastScore) {
  1264. // Alright! We found a better parent to use.
  1265. topCandidate = parentOfTopCandidate;
  1266. break;
  1267. }
  1268. lastScore = parentOfTopCandidate.readability.contentScore;
  1269. parentOfTopCandidate = parentOfTopCandidate.parentNode;
  1270. }
  1271. // If the top candidate is the only child, use parent instead. This will help sibling
  1272. // joining logic when adjacent content is actually located in parent's sibling node.
  1273. parentOfTopCandidate = topCandidate.parentNode;
  1274. while (
  1275. parentOfTopCandidate.tagName != "BODY" &&
  1276. parentOfTopCandidate.children.length == 1
  1277. ) {
  1278. topCandidate = parentOfTopCandidate;
  1279. parentOfTopCandidate = topCandidate.parentNode;
  1280. }
  1281. if (!topCandidate.readability) {
  1282. this._initializeNode(topCandidate);
  1283. }
  1284. }
  1285. // Now that we have the top candidate, look through its siblings for content
  1286. // that might also be related. Things like preambles, content split by ads
  1287. // that we removed, etc.
  1288. var articleContent = doc.createElement("DIV");
  1289. if (isPaging) {
  1290. articleContent.id = "readability-content";
  1291. }
  1292. var siblingScoreThreshold = Math.max(
  1293. 10,
  1294. topCandidate.readability.contentScore * 0.2
  1295. );
  1296. // Keep potential top candidate's parent node to try to get text direction of it later.
  1297. parentOfTopCandidate = topCandidate.parentNode;
  1298. var siblings = parentOfTopCandidate.children;
  1299. for (var s = 0, sl = siblings.length; s < sl; s++) {
  1300. var sibling = siblings[s];
  1301. var append = false;
  1302. this.log(
  1303. "Looking at sibling node:",
  1304. sibling,
  1305. sibling.readability
  1306. ? "with score " + sibling.readability.contentScore
  1307. : ""
  1308. );
  1309. this.log(
  1310. "Sibling has score",
  1311. sibling.readability ? sibling.readability.contentScore : "Unknown"
  1312. );
  1313. if (sibling === topCandidate) {
  1314. append = true;
  1315. } else {
  1316. var contentBonus = 0;
  1317. // Give a bonus if sibling nodes and top candidates have the example same classname
  1318. if (
  1319. sibling.className === topCandidate.className &&
  1320. topCandidate.className !== ""
  1321. ) {
  1322. contentBonus += topCandidate.readability.contentScore * 0.2;
  1323. }
  1324. if (
  1325. sibling.readability &&
  1326. sibling.readability.contentScore + contentBonus >=
  1327. siblingScoreThreshold
  1328. ) {
  1329. append = true;
  1330. } else if (sibling.nodeName === "P") {
  1331. var linkDensity = this._getLinkDensity(sibling);
  1332. var nodeContent = this._getInnerText(sibling);
  1333. var nodeLength = nodeContent.length;
  1334. if (nodeLength > 80 && linkDensity < 0.25) {
  1335. append = true;
  1336. } else if (
  1337. nodeLength < 80 &&
  1338. nodeLength > 0 &&
  1339. linkDensity === 0 &&
  1340. nodeContent.search(/\.( |$)/) !== -1
  1341. ) {
  1342. append = true;
  1343. }
  1344. }
  1345. }
  1346. if (append) {
  1347. this.log("Appending node:", sibling);
  1348. if (!this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)) {
  1349. // We have a node that isn't a common block level element, like a form or td tag.
  1350. // Turn it into a div so it doesn't get filtered out later by accident.
  1351. this.log("Altering sibling:", sibling, "to div.");
  1352. sibling = this._setNodeTag(sibling, "DIV");
  1353. }
  1354. articleContent.appendChild(sibling);
  1355. // Fetch children again to make it compatible
  1356. // with DOM parsers without live collection support.
  1357. siblings = parentOfTopCandidate.children;
  1358. // siblings is a reference to the children array, and
  1359. // sibling is removed from the array when we call appendChild().
  1360. // As a result, we must revisit this index since the nodes
  1361. // have been shifted.
  1362. s -= 1;
  1363. sl -= 1;
  1364. }
  1365. }
  1366. if (this._debug) {
  1367. this.log("Article content pre-prep: " + articleContent.innerHTML);
  1368. }
  1369. // So we have all of the content that we need. Now we clean it up for presentation.
  1370. this._prepArticle(articleContent);
  1371. if (this._debug) {
  1372. this.log("Article content post-prep: " + articleContent.innerHTML);
  1373. }
  1374. if (neededToCreateTopCandidate) {
  1375. // We already created a fake div thing, and there wouldn't have been any siblings left
  1376. // for the previous loop, so there's no point trying to create a new div, and then
  1377. // move all the children over. Just assign IDs and class names here. No need to append
  1378. // because that already happened anyway.
  1379. topCandidate.id = "readability-page-1";
  1380. topCandidate.className = "page";
  1381. } else {
  1382. var div = doc.createElement("DIV");
  1383. div.id = "readability-page-1";
  1384. div.className = "page";
  1385. while (articleContent.firstChild) {
  1386. div.appendChild(articleContent.firstChild);
  1387. }
  1388. articleContent.appendChild(div);
  1389. }
  1390. if (this._debug) {
  1391. this.log("Article content after paging: " + articleContent.innerHTML);
  1392. }
  1393. var parseSuccessful = true;
  1394. // Now that we've gone through the full algorithm, check to see if
  1395. // we got any meaningful content. If we didn't, we may need to re-run
  1396. // grabArticle with different flags set. This gives us a higher likelihood of
  1397. // finding the content, and the sieve approach gives us a higher likelihood of
  1398. // finding the -right- content.
  1399. var textLength = this._getInnerText(articleContent, true).length;
  1400. if (textLength < this._charThreshold) {
  1401. parseSuccessful = false;
  1402. // eslint-disable-next-line no-unsanitized/property
  1403. page.innerHTML = pageCacheHtml;
  1404. this._attempts.push({
  1405. articleContent,
  1406. textLength,
  1407. });
  1408. if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) {
  1409. this._removeFlag(this.FLAG_STRIP_UNLIKELYS);
  1410. } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
  1411. this._removeFlag(this.FLAG_WEIGHT_CLASSES);
  1412. } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
  1413. this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY);
  1414. } else {
  1415. // No luck after removing flags, just return the longest text we found during the different loops
  1416. this._attempts.sort(function (a, b) {
  1417. return b.textLength - a.textLength;
  1418. });
  1419. // But first check if we actually have something
  1420. if (!this._attempts[0].textLength) {
  1421. return null;
  1422. }
  1423. articleContent = this._attempts[0].articleContent;
  1424. parseSuccessful = true;
  1425. }
  1426. }
  1427. if (parseSuccessful) {
  1428. // Find out text direction from ancestors of final top candidate.
  1429. var ancestors = [parentOfTopCandidate, topCandidate].concat(
  1430. this._getNodeAncestors(parentOfTopCandidate)
  1431. );
  1432. this._someNode(ancestors, function (ancestor) {
  1433. if (!ancestor.tagName) {
  1434. return false;
  1435. }
  1436. var articleDir = ancestor.getAttribute("dir");
  1437. if (articleDir) {
  1438. this._articleDir = articleDir;
  1439. return true;
  1440. }
  1441. return false;
  1442. });
  1443. return articleContent;
  1444. }
  1445. }
  1446. },
  1447. /**
  1448. * Converts some of the common HTML entities in string to their corresponding characters.
  1449. *
  1450. * @param str {string} - a string to unescape.
  1451. * @return string without HTML entity.
  1452. */
  1453. _unescapeHtmlEntities(str) {
  1454. if (!str) {
  1455. return str;
  1456. }
  1457. var htmlEscapeMap = this.HTML_ESCAPE_MAP;
  1458. return str
  1459. .replace(/&(quot|amp|apos|lt|gt);/g, function (_, tag) {
  1460. return htmlEscapeMap[tag];
  1461. })
  1462. .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, numStr) {
  1463. var num = parseInt(hex || numStr, hex ? 16 : 10);
  1464. // these character references are replaced by a conforming HTML parser
  1465. if (num == 0 || num > 0x10ffff || (num >= 0xd800 && num <= 0xdfff)) {
  1466. num = 0xfffd;
  1467. }
  1468. return String.fromCodePoint(num);
  1469. });
  1470. },
  1471. /**
  1472. * Try to extract metadata from JSON-LD object.
  1473. * For now, only Schema.org objects of type Article or its subtypes are supported.
  1474. * @return Object with any metadata that could be extracted (possibly none)
  1475. */
  1476. _getJSONLD(doc) {
  1477. var scripts = this._getAllNodesWithTag(doc, ["script"]);
  1478. var metadata;
  1479. this._forEachNode(scripts, function (jsonLdElement) {
  1480. if (
  1481. !metadata &&
  1482. jsonLdElement.getAttribute("type") === "application/ld+json"
  1483. ) {
  1484. try {
  1485. // Strip CDATA markers if present
  1486. var content = jsonLdElement.textContent.replace(
  1487. /^\s*<!\[CDATA\[|\]\]>\s*$/g,
  1488. ""
  1489. );
  1490. var parsed = JSON.parse(content);
  1491. if (Array.isArray(parsed)) {
  1492. parsed = parsed.find(it => {
  1493. return (
  1494. it["@type"] &&
  1495. it["@type"].match(this.REGEXPS.jsonLdArticleTypes)
  1496. );
  1497. });
  1498. if (!parsed) {
  1499. return;
  1500. }
  1501. }
  1502. var schemaDotOrgRegex = /^https?\:\/\/schema\.org\/?$/;
  1503. var matches =
  1504. (typeof parsed["@context"] === "string" &&
  1505. parsed["@context"].match(schemaDotOrgRegex)) ||
  1506. (typeof parsed["@context"] === "object" &&
  1507. typeof parsed["@context"]["@vocab"] == "string" &&
  1508. parsed["@context"]["@vocab"].match(schemaDotOrgRegex));
  1509. if (!matches) {
  1510. return;
  1511. }
  1512. if (!parsed["@type"] && Array.isArray(parsed["@graph"])) {
  1513. parsed = parsed["@graph"].find(it => {
  1514. return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes);
  1515. });
  1516. }
  1517. if (
  1518. !parsed ||
  1519. !parsed["@type"] ||
  1520. !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes)
  1521. ) {
  1522. return;
  1523. }
  1524. metadata = {};
  1525. if (
  1526. typeof parsed.name === "string" &&
  1527. typeof parsed.headline === "string" &&
  1528. parsed.name !== parsed.headline
  1529. ) {
  1530. // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz
  1531. // put their own name into "name" and the article title to "headline" which confuses Readability. So we try to check if either
  1532. // "name" or "headline" closely matches the html title, and if so, use that one. If not, then we use "name" by default.
  1533. var title = this._getArticleTitle();
  1534. var nameMatches = this._textSimilarity(parsed.name, title) > 0.75;
  1535. var headlineMatches =
  1536. this._textSimilarity(parsed.headline, title) > 0.75;
  1537. if (headlineMatches && !nameMatches) {
  1538. metadata.title = parsed.headline;
  1539. } else {
  1540. metadata.title = parsed.name;
  1541. }
  1542. } else if (typeof parsed.name === "string") {
  1543. metadata.title = parsed.name.trim();
  1544. } else if (typeof parsed.headline === "string") {
  1545. metadata.title = parsed.headline.trim();
  1546. }
  1547. if (parsed.author) {
  1548. if (typeof parsed.author.name === "string") {
  1549. metadata.byline = parsed.author.name.trim();
  1550. } else if (
  1551. Array.isArray(parsed.author) &&
  1552. parsed.author[0] &&
  1553. typeof parsed.author[0].name === "string"
  1554. ) {
  1555. metadata.byline = parsed.author
  1556. .filter(function (author) {
  1557. return author && typeof author.name === "string";
  1558. })
  1559. .map(function (author) {
  1560. return author.name.trim();
  1561. })
  1562. .join(", ");
  1563. }
  1564. }
  1565. if (typeof parsed.description === "string") {
  1566. metadata.excerpt = parsed.description.trim();
  1567. }
  1568. if (parsed.publisher && typeof parsed.publisher.name === "string") {
  1569. metadata.siteName = parsed.publisher.name.trim();
  1570. }
  1571. if (typeof parsed.datePublished === "string") {
  1572. metadata.datePublished = parsed.datePublished.trim();
  1573. }
  1574. } catch (err) {
  1575. this.log(err.message);
  1576. }
  1577. }
  1578. });
  1579. return metadata ? metadata : {};
  1580. },
  1581. /**
  1582. * Attempts to get excerpt and byline metadata for the article.
  1583. *
  1584. * @param {Object} jsonld — object containing any metadata that
  1585. * could be extracted from JSON-LD object.
  1586. *
  1587. * @return Object with optional "excerpt" and "byline" properties
  1588. */
  1589. _getArticleMetadata(jsonld) {
  1590. var metadata = {};
  1591. var values = {};
  1592. var metaElements = this._doc.getElementsByTagName("meta");
  1593. // property is a space-separated list of values
  1594. var propertyPattern =
  1595. /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi;
  1596. // name is a single value
  1597. var namePattern =
  1598. /^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i;
  1599. // Find description tags.
  1600. this._forEachNode(metaElements, function (element) {
  1601. var elementName = element.getAttribute("name");
  1602. var elementProperty = element.getAttribute("property");
  1603. var content = element.getAttribute("content");
  1604. if (!content) {
  1605. return;
  1606. }
  1607. var matches = null;
  1608. var name = null;
  1609. if (elementProperty) {
  1610. matches = elementProperty.match(propertyPattern);
  1611. if (matches) {
  1612. // Convert to lowercase, and remove any whitespace
  1613. // so we can match below.
  1614. name = matches[0].toLowerCase().replace(/\s/g, "");
  1615. // multiple authors
  1616. values[name] = content.trim();
  1617. }
  1618. }
  1619. if (!matches && elementName && namePattern.test(elementName)) {
  1620. name = elementName;
  1621. if (content) {
  1622. // Convert to lowercase, remove any whitespace, and convert dots
  1623. // to colons so we can match below.
  1624. name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":");
  1625. values[name] = content.trim();
  1626. }
  1627. }
  1628. });
  1629. // get title
  1630. metadata.title =
  1631. jsonld.title ||
  1632. values["dc:title"] ||
  1633. values["dcterm:title"] ||
  1634. values["og:title"] ||
  1635. values["weibo:article:title"] ||
  1636. values["weibo:webpage:title"] ||
  1637. values.title ||
  1638. values["twitter:title"] ||
  1639. values["parsely-title"];
  1640. if (!metadata.title) {
  1641. metadata.title = this._getArticleTitle();
  1642. }
  1643. const articleAuthor =
  1644. typeof values["article:author"] === "string" &&
  1645. !this._isUrl(values["article:author"])
  1646. ? values["article:author"]
  1647. : undefined;
  1648. // get author
  1649. metadata.byline =
  1650. jsonld.byline ||
  1651. values["dc:creator"] ||
  1652. values["dcterm:creator"] ||
  1653. values.author ||
  1654. values["parsely-author"] ||
  1655. articleAuthor;
  1656. // get description
  1657. metadata.excerpt =
  1658. jsonld.excerpt ||
  1659. values["dc:description"] ||
  1660. values["dcterm:description"] ||
  1661. values["og:description"] ||
  1662. values["weibo:article:description"] ||
  1663. values["weibo:webpage:description"] ||
  1664. values.description ||
  1665. values["twitter:description"];
  1666. // get site name
  1667. metadata.siteName = jsonld.siteName || values["og:site_name"];
  1668. // get article published time
  1669. metadata.publishedTime =
  1670. jsonld.datePublished ||
  1671. values["article:published_time"] ||
  1672. values["parsely-pub-date"] ||
  1673. null;
  1674. // in many sites the meta value is escaped with HTML entities,
  1675. // so here we need to unescape it
  1676. metadata.title = this._unescapeHtmlEntities(metadata.title);
  1677. metadata.byline = this._unescapeHtmlEntities(metadata.byline);
  1678. metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt);
  1679. metadata.siteName = this._unescapeHtmlEntities(metadata.siteName);
  1680. metadata.publishedTime = this._unescapeHtmlEntities(metadata.publishedTime);
  1681. return metadata;
  1682. },
  1683. /**
  1684. * Check if node is image, or if node contains exactly only one image
  1685. * whether as a direct child or as its descendants.
  1686. *
  1687. * @param Element
  1688. **/
  1689. _isSingleImage(node) {
  1690. while (node) {
  1691. if (node.tagName === "IMG") {
  1692. return true;
  1693. }
  1694. if (node.children.length !== 1 || node.textContent.trim() !== "") {
  1695. return false;
  1696. }
  1697. node = node.children[0];
  1698. }
  1699. return false;
  1700. },
  1701. /**
  1702. * Find all <noscript> that are located after <img> nodes, and which contain only one
  1703. * <img> element. Replace the first image with the image from inside the <noscript> tag,
  1704. * and remove the <noscript> tag. This improves the quality of the images we use on
  1705. * some sites (e.g. Medium).
  1706. *
  1707. * @param Element
  1708. **/
  1709. _unwrapNoscriptImages(doc) {
  1710. // Find img without source or attributes that might contains image, and remove it.
  1711. // This is done to prevent a placeholder img is replaced by img from noscript in next step.
  1712. var imgs = Array.from(doc.getElementsByTagName("img"));
  1713. this._forEachNode(imgs, function (img) {
  1714. for (var i = 0; i < img.attributes.length; i++) {
  1715. var attr = img.attributes[i];
  1716. switch (attr.name) {
  1717. case "src":
  1718. case "srcset":
  1719. case "data-src":
  1720. case "data-srcset":
  1721. return;
  1722. }
  1723. if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  1724. return;
  1725. }
  1726. }
  1727. img.remove();
  1728. });
  1729. // Next find noscript and try to extract its image
  1730. var noscripts = Array.from(doc.getElementsByTagName("noscript"));
  1731. this._forEachNode(noscripts, function (noscript) {
  1732. // Parse content of noscript and make sure it only contains image
  1733. if (!this._isSingleImage(noscript)) {
  1734. return;
  1735. }
  1736. var tmp = doc.createElement("div");
  1737. // We're running in the document context, and using unmodified
  1738. // document contents, so doing this should be safe.
  1739. // (Also we heavily discourage people from allowing script to
  1740. // run at all in this document...)
  1741. // eslint-disable-next-line no-unsanitized/property
  1742. tmp.innerHTML = noscript.innerHTML;
  1743. // If noscript has previous sibling and it only contains image,
  1744. // replace it with noscript content. However we also keep old
  1745. // attributes that might contains image.
  1746. var prevElement = noscript.previousElementSibling;
  1747. if (prevElement && this._isSingleImage(prevElement)) {
  1748. var prevImg = prevElement;
  1749. if (prevImg.tagName !== "IMG") {
  1750. prevImg = prevElement.getElementsByTagName("img")[0];
  1751. }
  1752. var newImg = tmp.getElementsByTagName("img")[0];
  1753. for (var i = 0; i < prevImg.attributes.length; i++) {
  1754. var attr = prevImg.attributes[i];
  1755. if (attr.value === "") {
  1756. continue;
  1757. }
  1758. if (
  1759. attr.name === "src" ||
  1760. attr.name === "srcset" ||
  1761. /\.(jpg|jpeg|png|webp)/i.test(attr.value)
  1762. ) {
  1763. if (newImg.getAttribute(attr.name) === attr.value) {
  1764. continue;
  1765. }
  1766. var attrName = attr.name;
  1767. if (newImg.hasAttribute(attrName)) {
  1768. attrName = "data-old-" + attrName;
  1769. }
  1770. newImg.setAttribute(attrName, attr.value);
  1771. }
  1772. }
  1773. noscript.parentNode.replaceChild(tmp.firstElementChild, prevElement);
  1774. }
  1775. });
  1776. },
  1777. /**
  1778. * Removes script tags from the document.
  1779. *
  1780. * @param Element
  1781. **/
  1782. _removeScripts(doc) {
  1783. this._removeNodes(this._getAllNodesWithTag(doc, ["script", "noscript"]));
  1784. },
  1785. /**
  1786. * Check if this node has only whitespace and a single element with given tag
  1787. * Returns false if the DIV node contains non-empty text nodes
  1788. * or if it contains no element with given tag or more than 1 element.
  1789. *
  1790. * @param Element
  1791. * @param string tag of child element
  1792. **/
  1793. _hasSingleTagInsideElement(element, tag) {
  1794. // There should be exactly 1 element child with given tag
  1795. if (element.children.length != 1 || element.children[0].tagName !== tag) {
  1796. return false;
  1797. }
  1798. // And there should be no text nodes with real content
  1799. return !this._someNode(element.childNodes, function (node) {
  1800. return (
  1801. node.nodeType === this.TEXT_NODE &&
  1802. this.REGEXPS.hasContent.test(node.textContent)
  1803. );
  1804. });
  1805. },
  1806. _isElementWithoutContent(node) {
  1807. return (
  1808. node.nodeType === this.ELEMENT_NODE &&
  1809. !node.textContent.trim().length &&
  1810. (!node.children.length ||
  1811. node.children.length ==
  1812. node.getElementsByTagName("br").length +
  1813. node.getElementsByTagName("hr").length)
  1814. );
  1815. },
  1816. /**
  1817. * Determine whether element has any children block level elements.
  1818. *
  1819. * @param Element
  1820. */
  1821. _hasChildBlockElement(element) {
  1822. return this._someNode(element.childNodes, function (node) {
  1823. return (
  1824. this.DIV_TO_P_ELEMS.has(node.tagName) ||
  1825. this._hasChildBlockElement(node)
  1826. );
  1827. });
  1828. },
  1829. /***
  1830. * Determine if a node qualifies as phrasing content.
  1831. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
  1832. **/
  1833. _isPhrasingContent(node) {
  1834. return (
  1835. node.nodeType === this.TEXT_NODE ||
  1836. this.PHRASING_ELEMS.includes(node.tagName) ||
  1837. ((node.tagName === "A" ||
  1838. node.tagName === "DEL" ||
  1839. node.tagName === "INS") &&
  1840. this._everyNode(node.childNodes, this._isPhrasingContent))
  1841. );
  1842. },
  1843. _isWhitespace(node) {
  1844. return (
  1845. (node.nodeType === this.TEXT_NODE &&
  1846. node.textContent.trim().length === 0) ||
  1847. (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR")
  1848. );
  1849. },
  1850. /**
  1851. * Get the inner text of a node - cross browser compatibly.
  1852. * This also strips out any excess whitespace to be found.
  1853. *
  1854. * @param Element
  1855. * @param Boolean normalizeSpaces (default: true)
  1856. * @return string
  1857. **/
  1858. _getInnerText(e, normalizeSpaces) {
  1859. normalizeSpaces =
  1860. typeof normalizeSpaces === "undefined" ? true : normalizeSpaces;
  1861. var textContent = e.textContent.trim();
  1862. if (normalizeSpaces) {
  1863. return textContent.replace(this.REGEXPS.normalize, " ");
  1864. }
  1865. return textContent;
  1866. },
  1867. /**
  1868. * Get the number of times a string s appears in the node e.
  1869. *
  1870. * @param Element
  1871. * @param string - what to split on. Default is ","
  1872. * @return number (integer)
  1873. **/
  1874. _getCharCount(e, s) {
  1875. s = s || ",";
  1876. return this._getInnerText(e).split(s).length - 1;
  1877. },
  1878. /**
  1879. * Remove the style attribute on every e and under.
  1880. * TODO: Test if getElementsByTagName(*) is faster.
  1881. *
  1882. * @param Element
  1883. * @return void
  1884. **/
  1885. _cleanStyles(e) {
  1886. if (!e || e.tagName.toLowerCase() === "svg") {
  1887. return;
  1888. }
  1889. // Remove `style` and deprecated presentational attributes
  1890. for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) {
  1891. e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]);
  1892. }
  1893. if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.includes(e.tagName)) {
  1894. e.removeAttribute("width");
  1895. e.removeAttribute("height");
  1896. }
  1897. var cur = e.firstElementChild;
  1898. while (cur !== null) {
  1899. this._cleanStyles(cur);
  1900. cur = cur.nextElementSibling;
  1901. }
  1902. },
  1903. /**
  1904. * Get the density of links as a percentage of the content
  1905. * This is the amount of text that is inside a link divided by the total text in the node.
  1906. *
  1907. * @param Element
  1908. * @return number (float)
  1909. **/
  1910. _getLinkDensity(element) {
  1911. var textLength = this._getInnerText(element).length;
  1912. if (textLength === 0) {
  1913. return 0;
  1914. }
  1915. var linkLength = 0;
  1916. // XXX implement _reduceNodeList?
  1917. this._forEachNode(element.getElementsByTagName("a"), function (linkNode) {
  1918. var href = linkNode.getAttribute("href");
  1919. var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1;
  1920. linkLength += this._getInnerText(linkNode).length * coefficient;
  1921. });
  1922. return linkLength / textLength;
  1923. },
  1924. /**
  1925. * Get an elements class/id weight. Uses regular expressions to tell if this
  1926. * element looks good or bad.
  1927. *
  1928. * @param Element
  1929. * @return number (Integer)
  1930. **/
  1931. _getClassWeight(e) {
  1932. if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) {
  1933. return 0;
  1934. }
  1935. var weight = 0;
  1936. // Look for a special classname
  1937. if (typeof e.className === "string" && e.className !== "") {
  1938. if (this.REGEXPS.negative.test(e.className)) {
  1939. weight -= 25;
  1940. }
  1941. if (this.REGEXPS.positive.test(e.className)) {
  1942. weight += 25;
  1943. }
  1944. }
  1945. // Look for a special ID
  1946. if (typeof e.id === "string" && e.id !== "") {
  1947. if (this.REGEXPS.negative.test(e.id)) {
  1948. weight -= 25;
  1949. }
  1950. if (this.REGEXPS.positive.test(e.id)) {
  1951. weight += 25;
  1952. }
  1953. }
  1954. return weight;
  1955. },
  1956. /**
  1957. * Clean a node of all elements of type "tag".
  1958. * (Unless it's a youtube/vimeo video. People love movies.)
  1959. *
  1960. * @param Element
  1961. * @param string tag to clean
  1962. * @return void
  1963. **/
  1964. _clean(e, tag) {
  1965. var isEmbed = ["object", "embed", "iframe"].includes(tag);
  1966. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (element) {
  1967. // Allow youtube and vimeo videos through as people usually want to see those.
  1968. if (isEmbed) {
  1969. // First, check the elements attributes to see if any of them contain youtube or vimeo
  1970. for (var i = 0; i < element.attributes.length; i++) {
  1971. if (this._allowedVideoRegex.test(element.attributes[i].value)) {
  1972. return false;
  1973. }
  1974. }
  1975. // For embed with <object> tag, check inner HTML as well.
  1976. if (
  1977. element.tagName === "object" &&
  1978. this._allowedVideoRegex.test(element.innerHTML)
  1979. ) {
  1980. return false;
  1981. }
  1982. }
  1983. return true;
  1984. });
  1985. },
  1986. /**
  1987. * Check if a given node has one of its ancestor tag name matching the
  1988. * provided one.
  1989. * @param HTMLElement node
  1990. * @param String tagName
  1991. * @param Number maxDepth
  1992. * @param Function filterFn a filter to invoke to determine whether this node 'counts'
  1993. * @return Boolean
  1994. */
  1995. _hasAncestorTag(node, tagName, maxDepth, filterFn) {
  1996. maxDepth = maxDepth || 3;
  1997. tagName = tagName.toUpperCase();
  1998. var depth = 0;
  1999. while (node.parentNode) {
  2000. if (maxDepth > 0 && depth > maxDepth) {
  2001. return false;
  2002. }
  2003. if (
  2004. node.parentNode.tagName === tagName &&
  2005. (!filterFn || filterFn(node.parentNode))
  2006. ) {
  2007. return true;
  2008. }
  2009. node = node.parentNode;
  2010. depth++;
  2011. }
  2012. return false;
  2013. },
  2014. /**
  2015. * Return an object indicating how many rows and columns this table has.
  2016. */
  2017. _getRowAndColumnCount(table) {
  2018. var rows = 0;
  2019. var columns = 0;
  2020. var trs = table.getElementsByTagName("tr");
  2021. for (var i = 0; i < trs.length; i++) {
  2022. var rowspan = trs[i].getAttribute("rowspan") || 0;
  2023. if (rowspan) {
  2024. rowspan = parseInt(rowspan, 10);
  2025. }
  2026. rows += rowspan || 1;
  2027. // Now look for column-related info
  2028. var columnsInThisRow = 0;
  2029. var cells = trs[i].getElementsByTagName("td");
  2030. for (var j = 0; j < cells.length; j++) {
  2031. var colspan = cells[j].getAttribute("colspan") || 0;
  2032. if (colspan) {
  2033. colspan = parseInt(colspan, 10);
  2034. }
  2035. columnsInThisRow += colspan || 1;
  2036. }
  2037. columns = Math.max(columns, columnsInThisRow);
  2038. }
  2039. return { rows, columns };
  2040. },
  2041. /**
  2042. * Look for 'data' (as opposed to 'layout') tables, for which we use
  2043. * similar checks as
  2044. * https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/accessible/generic/TableAccessible.cpp#19
  2045. */
  2046. _markDataTables(root) {
  2047. var tables = root.getElementsByTagName("table");
  2048. for (var i = 0; i < tables.length; i++) {
  2049. var table = tables[i];
  2050. var role = table.getAttribute("role");
  2051. if (role == "presentation") {
  2052. table._readabilityDataTable = false;
  2053. continue;
  2054. }
  2055. var datatable = table.getAttribute("datatable");
  2056. if (datatable == "0") {
  2057. table._readabilityDataTable = false;
  2058. continue;
  2059. }
  2060. var summary = table.getAttribute("summary");
  2061. if (summary) {
  2062. table._readabilityDataTable = true;
  2063. continue;
  2064. }
  2065. var caption = table.getElementsByTagName("caption")[0];
  2066. if (caption && caption.childNodes.length) {
  2067. table._readabilityDataTable = true;
  2068. continue;
  2069. }
  2070. // If the table has a descendant with any of these tags, consider a data table:
  2071. var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"];
  2072. var descendantExists = function (tag) {
  2073. return !!table.getElementsByTagName(tag)[0];
  2074. };
  2075. if (dataTableDescendants.some(descendantExists)) {
  2076. this.log("Data table because found data-y descendant");
  2077. table._readabilityDataTable = true;
  2078. continue;
  2079. }
  2080. // Nested tables indicate a layout table:
  2081. if (table.getElementsByTagName("table")[0]) {
  2082. table._readabilityDataTable = false;
  2083. continue;
  2084. }
  2085. var sizeInfo = this._getRowAndColumnCount(table);
  2086. if (sizeInfo.columns == 1 || sizeInfo.rows == 1) {
  2087. // single colum/row tables are commonly used for page layout purposes.
  2088. table._readabilityDataTable = false;
  2089. continue;
  2090. }
  2091. if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) {
  2092. table._readabilityDataTable = true;
  2093. continue;
  2094. }
  2095. // Now just go by size entirely:
  2096. table._readabilityDataTable = sizeInfo.rows * sizeInfo.columns > 10;
  2097. }
  2098. },
  2099. /* convert images and figures that have properties like data-src into images that can be loaded without JS */
  2100. _fixLazyImages(root) {
  2101. this._forEachNode(
  2102. this._getAllNodesWithTag(root, ["img", "picture", "figure"]),
  2103. function (elem) {
  2104. // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute.
  2105. // So, here we check if the data uri is too short, just might as well remove it.
  2106. if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) {
  2107. // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes.
  2108. var parts = this.REGEXPS.b64DataUrl.exec(elem.src);
  2109. if (parts[1] === "image/svg+xml") {
  2110. return;
  2111. }
  2112. // Make sure this element has other attributes which contains image.
  2113. // If it doesn't, then this src is important and shouldn't be removed.
  2114. var srcCouldBeRemoved = false;
  2115. for (var i = 0; i < elem.attributes.length; i++) {
  2116. var attr = elem.attributes[i];
  2117. if (attr.name === "src") {
  2118. continue;
  2119. }
  2120. if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) {
  2121. srcCouldBeRemoved = true;
  2122. break;
  2123. }
  2124. }
  2125. // Here we assume if image is less than 100 bytes (or 133 after encoded to base64)
  2126. // it will be too small, therefore it might be placeholder image.
  2127. if (srcCouldBeRemoved) {
  2128. var b64starts = parts[0].length;
  2129. var b64length = elem.src.length - b64starts;
  2130. if (b64length < 133) {
  2131. elem.removeAttribute("src");
  2132. }
  2133. }
  2134. }
  2135. // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580
  2136. if (
  2137. (elem.src || (elem.srcset && elem.srcset != "null")) &&
  2138. !elem.className.toLowerCase().includes("lazy")
  2139. ) {
  2140. return;
  2141. }
  2142. for (var j = 0; j < elem.attributes.length; j++) {
  2143. attr = elem.attributes[j];
  2144. if (
  2145. attr.name === "src" ||
  2146. attr.name === "srcset" ||
  2147. attr.name === "alt"
  2148. ) {
  2149. continue;
  2150. }
  2151. var copyTo = null;
  2152. if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) {
  2153. copyTo = "srcset";
  2154. } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) {
  2155. copyTo = "src";
  2156. }
  2157. if (copyTo) {
  2158. //if this is an img or picture, set the attribute directly
  2159. if (elem.tagName === "IMG" || elem.tagName === "PICTURE") {
  2160. elem.setAttribute(copyTo, attr.value);
  2161. } else if (
  2162. elem.tagName === "FIGURE" &&
  2163. !this._getAllNodesWithTag(elem, ["img", "picture"]).length
  2164. ) {
  2165. //if the item is a <figure> that does not contain an image or picture, create one and place it inside the figure
  2166. //see the nytimes-3 testcase for an example
  2167. var img = this._doc.createElement("img");
  2168. img.setAttribute(copyTo, attr.value);
  2169. elem.appendChild(img);
  2170. }
  2171. }
  2172. }
  2173. }
  2174. );
  2175. },
  2176. _getTextDensity(e, tags) {
  2177. var textLength = this._getInnerText(e, true).length;
  2178. if (textLength === 0) {
  2179. return 0;
  2180. }
  2181. var childrenLength = 0;
  2182. var children = this._getAllNodesWithTag(e, tags);
  2183. this._forEachNode(
  2184. children,
  2185. child => (childrenLength += this._getInnerText(child, true).length)
  2186. );
  2187. return childrenLength / textLength;
  2188. },
  2189. /**
  2190. * Clean an element of all tags of type "tag" if they look fishy.
  2191. * "Fishy" is an algorithm based on content length, classnames, link density, number of images & embeds, etc.
  2192. *
  2193. * @return void
  2194. **/
  2195. _cleanConditionally(e, tag) {
  2196. if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) {
  2197. return;
  2198. }
  2199. // Gather counts for other typical elements embedded within.
  2200. // Traverse backwards so we can remove nodes at the same time
  2201. // without effecting the traversal.
  2202. //
  2203. // TODO: Consider taking into account original contentScore here.
  2204. this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (node) {
  2205. // First check if this node IS data table, in which case don't remove it.
  2206. var isDataTable = function (t) {
  2207. return t._readabilityDataTable;
  2208. };
  2209. var isList = tag === "ul" || tag === "ol";
  2210. if (!isList) {
  2211. var listLength = 0;
  2212. var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]);
  2213. this._forEachNode(
  2214. listNodes,
  2215. list => (listLength += this._getInnerText(list).length)
  2216. );
  2217. isList = listLength / this._getInnerText(node).length > 0.9;
  2218. }
  2219. if (tag === "table" && isDataTable(node)) {
  2220. return false;
  2221. }
  2222. // Next check if we're inside a data table, in which case don't remove it as well.
  2223. if (this._hasAncestorTag(node, "table", -1, isDataTable)) {
  2224. return false;
  2225. }
  2226. if (this._hasAncestorTag(node, "code")) {
  2227. return false;
  2228. }
  2229. // keep element if it has a data tables
  2230. if (
  2231. [...node.getElementsByTagName("table")].some(
  2232. tbl => tbl._readabilityDataTable
  2233. )
  2234. ) {
  2235. return false;
  2236. }
  2237. var weight = this._getClassWeight(node);
  2238. this.log("Cleaning Conditionally", node);
  2239. var contentScore = 0;
  2240. if (weight + contentScore < 0) {
  2241. return true;
  2242. }
  2243. if (this._getCharCount(node, ",") < 10) {
  2244. // If there are not very many commas, and the number of
  2245. // non-paragraph elements is more than paragraphs or other
  2246. // ominous signs, remove the element.
  2247. var p = node.getElementsByTagName("p").length;
  2248. var img = node.getElementsByTagName("img").length;
  2249. var li = node.getElementsByTagName("li").length - 100;
  2250. var input = node.getElementsByTagName("input").length;
  2251. var headingDensity = this._getTextDensity(node, [
  2252. "h1",
  2253. "h2",
  2254. "h3",
  2255. "h4",
  2256. "h5",
  2257. "h6",
  2258. ]);
  2259. var embedCount = 0;
  2260. var embeds = this._getAllNodesWithTag(node, [
  2261. "object",
  2262. "embed",
  2263. "iframe",
  2264. ]);
  2265. for (var i = 0; i < embeds.length; i++) {
  2266. // If this embed has attribute that matches video regex, don't delete it.
  2267. for (var j = 0; j < embeds[i].attributes.length; j++) {
  2268. if (this._allowedVideoRegex.test(embeds[i].attributes[j].value)) {
  2269. return false;
  2270. }
  2271. }
  2272. // For embed with <object> tag, check inner HTML as well.
  2273. if (
  2274. embeds[i].tagName === "object" &&
  2275. this._allowedVideoRegex.test(embeds[i].innerHTML)
  2276. ) {
  2277. return false;
  2278. }
  2279. embedCount++;
  2280. }
  2281. var innerText = this._getInnerText(node);
  2282. // toss any node whose inner text contains nothing but suspicious words
  2283. if (
  2284. this.REGEXPS.adWords.test(innerText) ||
  2285. this.REGEXPS.loadingWords.test(innerText)
  2286. ) {
  2287. return true;
  2288. }
  2289. var contentLength = innerText.length;
  2290. var linkDensity = this._getLinkDensity(node);
  2291. var textishTags = ["SPAN", "LI", "TD"].concat(
  2292. Array.from(this.DIV_TO_P_ELEMS)
  2293. );
  2294. var textDensity = this._getTextDensity(node, textishTags);
  2295. var isFigureChild = this._hasAncestorTag(node, "figure");
  2296. // apply shadiness checks, then check for exceptions
  2297. const shouldRemoveNode = () => {
  2298. const errs = [];
  2299. if (!isFigureChild && img > 1 && p / img < 0.5) {
  2300. errs.push(`Bad p to img ratio (img=${img}, p=${p})`);
  2301. }
  2302. if (!isList && li > p) {
  2303. errs.push(`Too many li's outside of a list. (li=${li} > p=${p})`);
  2304. }
  2305. if (input > Math.floor(p / 3)) {
  2306. errs.push(`Too many inputs per p. (input=${input}, p=${p})`);
  2307. }
  2308. if (
  2309. !isList &&
  2310. !isFigureChild &&
  2311. headingDensity < 0.9 &&
  2312. contentLength < 25 &&
  2313. (img === 0 || img > 2) &&
  2314. linkDensity > 0
  2315. ) {
  2316. errs.push(
  2317. `Suspiciously short. (headingDensity=${headingDensity}, img=${img}, linkDensity=${linkDensity})`
  2318. );
  2319. }
  2320. if (
  2321. !isList &&
  2322. weight < 25 &&
  2323. linkDensity > 0.2 + this._linkDensityModifier
  2324. ) {
  2325. errs.push(
  2326. `Low weight and a little linky. (linkDensity=${linkDensity})`
  2327. );
  2328. }
  2329. if (weight >= 25 && linkDensity > 0.5 + this._linkDensityModifier) {
  2330. errs.push(
  2331. `High weight and mostly links. (linkDensity=${linkDensity})`
  2332. );
  2333. }
  2334. if ((embedCount === 1 && contentLength < 75) || embedCount > 1) {
  2335. errs.push(
  2336. `Suspicious embed. (embedCount=${embedCount}, contentLength=${contentLength})`
  2337. );
  2338. }
  2339. if (img === 0 && textDensity === 0) {
  2340. errs.push(
  2341. `No useful content. (img=${img}, textDensity=${textDensity})`
  2342. );
  2343. }
  2344. if (errs.length) {
  2345. this.log("Checks failed", errs);
  2346. return true;
  2347. }
  2348. return false;
  2349. };
  2350. var haveToRemove = shouldRemoveNode();
  2351. // Allow simple lists of images to remain in pages
  2352. if (isList && haveToRemove) {
  2353. for (var x = 0; x < node.children.length; x++) {
  2354. let child = node.children[x];
  2355. // Don't filter in lists with li's that contain more than one child
  2356. if (child.children.length > 1) {
  2357. return haveToRemove;
  2358. }
  2359. }
  2360. let li_count = node.getElementsByTagName("li").length;
  2361. // Only allow the list to remain if every li contains an image
  2362. if (img == li_count) {
  2363. return false;
  2364. }
  2365. }
  2366. return haveToRemove;
  2367. }
  2368. return false;
  2369. });
  2370. },
  2371. /**
  2372. * Clean out elements that match the specified conditions
  2373. *
  2374. * @param Element
  2375. * @param Function determines whether a node should be removed
  2376. * @return void
  2377. **/
  2378. _cleanMatchedNodes(e, filter) {
  2379. var endOfSearchMarkerNode = this._getNextNode(e, true);
  2380. var next = this._getNextNode(e);
  2381. while (next && next != endOfSearchMarkerNode) {
  2382. if (filter.call(this, next, next.className + " " + next.id)) {
  2383. next = this._removeAndGetNext(next);
  2384. } else {
  2385. next = this._getNextNode(next);
  2386. }
  2387. }
  2388. },
  2389. /**
  2390. * Clean out spurious headers from an Element.
  2391. *
  2392. * @param Element
  2393. * @return void
  2394. **/
  2395. _cleanHeaders(e) {
  2396. let headingNodes = this._getAllNodesWithTag(e, ["h1", "h2"]);
  2397. this._removeNodes(headingNodes, function (node) {
  2398. let shouldRemove = this._getClassWeight(node) < 0;
  2399. if (shouldRemove) {
  2400. this.log("Removing header with low class weight:", node);
  2401. }
  2402. return shouldRemove;
  2403. });
  2404. },
  2405. /**
  2406. * Check if this node is an H1 or H2 element whose content is mostly
  2407. * the same as the article title.
  2408. *
  2409. * @param Element the node to check.
  2410. * @return boolean indicating whether this is a title-like header.
  2411. */
  2412. _headerDuplicatesTitle(node) {
  2413. if (node.tagName != "H1" && node.tagName != "H2") {
  2414. return false;
  2415. }
  2416. var heading = this._getInnerText(node, false);
  2417. this.log("Evaluating similarity of header:", heading, this._articleTitle);
  2418. return this._textSimilarity(this._articleTitle, heading) > 0.75;
  2419. },
  2420. _flagIsActive(flag) {
  2421. return (this._flags & flag) > 0;
  2422. },
  2423. _removeFlag(flag) {
  2424. this._flags = this._flags & ~flag;
  2425. },
  2426. _isProbablyVisible(node) {
  2427. // Have to null-check node.style and node.className.includes to deal with SVG and MathML nodes.
  2428. return (
  2429. (!node.style || node.style.display != "none") &&
  2430. (!node.style || node.style.visibility != "hidden") &&
  2431. !node.hasAttribute("hidden") &&
  2432. //check for "fallback-image" so that wikimedia math images are displayed
  2433. (!node.hasAttribute("aria-hidden") ||
  2434. node.getAttribute("aria-hidden") != "true" ||
  2435. (node.className &&
  2436. node.className.includes &&
  2437. node.className.includes("fallback-image")))
  2438. );
  2439. },
  2440. /**
  2441. * Runs readability.
  2442. *
  2443. * Workflow:
  2444. * 1. Prep the document by removing script tags, css, etc.
  2445. * 2. Build readability's DOM tree.
  2446. * 3. Grab the article content from the current dom tree.
  2447. * 4. Replace the current DOM tree with the new one.
  2448. * 5. Read peacefully.
  2449. *
  2450. * @return void
  2451. **/
  2452. parse() {
  2453. // Avoid parsing too large documents, as per configuration option
  2454. if (this._maxElemsToParse > 0) {
  2455. var numTags = this._doc.getElementsByTagName("*").length;
  2456. if (numTags > this._maxElemsToParse) {
  2457. throw new Error(
  2458. "Aborting parsing document; " + numTags + " elements found"
  2459. );
  2460. }
  2461. }
  2462. // Unwrap image from noscript
  2463. this._unwrapNoscriptImages(this._doc);
  2464. // Extract JSON-LD metadata before removing scripts
  2465. var jsonLd = this._disableJSONLD ? {} : this._getJSONLD(this._doc);
  2466. // Remove script tags from the document.
  2467. this._removeScripts(this._doc);
  2468. this._prepDocument();
  2469. var metadata = this._getArticleMetadata(jsonLd);
  2470. this._metadata = metadata;
  2471. this._articleTitle = metadata.title;
  2472. var articleContent = this._grabArticle();
  2473. if (!articleContent) {
  2474. return null;
  2475. }
  2476. this.log("Grabbed: " + articleContent.innerHTML);
  2477. this._postProcessContent(articleContent);
  2478. // If we haven't found an excerpt in the article's metadata, use the article's
  2479. // first paragraph as the excerpt. This is used for displaying a preview of
  2480. // the article's content.
  2481. if (!metadata.excerpt) {
  2482. var paragraphs = articleContent.getElementsByTagName("p");
  2483. if (paragraphs.length) {
  2484. metadata.excerpt = paragraphs[0].textContent.trim();
  2485. }
  2486. }
  2487. var textContent = articleContent.textContent;
  2488. return {
  2489. title: this._articleTitle,
  2490. byline: metadata.byline || this._articleByline,
  2491. dir: this._articleDir,
  2492. lang: this._articleLang,
  2493. content: this._serializer(articleContent),
  2494. textContent,
  2495. length: textContent.length,
  2496. excerpt: metadata.excerpt,
  2497. siteName: metadata.siteName || this._articleSiteName,
  2498. publishedTime: metadata.publishedTime,
  2499. };
  2500. },
  2501. };
  2502. if (typeof module === "object") {
  2503. /* eslint-disable-next-line no-redeclare */
  2504. /* global module */
  2505. module.exports = Readability;
  2506. }