-
Notifications
You must be signed in to change notification settings - Fork 0
/
readability.js
1783 lines (1512 loc) · 70.4 KB
/
readability.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*jslint undef: true, nomen: true, eqeqeq: true, plusplus: true, newcap: true, immed: true, browser: true, devel: true, passfail: false */
/*global window: false, readConvertLinksToFootnotes: false, readStyle: false, readSize: false, readMargin: false, Typekit: false, ActiveXObject: false */
var dbg = (typeof console !== 'undefined') ? function(s) {
// console.log("Readability: " + s);
} : function() {};
/*
* Readability. An Arc90 Lab Experiment.
* Website: http://lab.arc90.com/experiments/readability
* Source: http://code.google.com/p/arc90labs-readability
*
* "Readability" is a trademark of Arc90 Inc and may not be used without explicit permission.
*
* Copyright (c) 2010 Arc90 Inc
* Readability is licensed under the Apache License, Version 2.0.
**/
var readability = {
version: '1.7.1',
iframeLoads: 0,
convertLinksToFootnotes: false,
reversePageScroll: false, /* If they hold shift and hit space, scroll up */
frameHack: false, /**
* The frame hack is to workaround a firefox bug where if you
* pull content out of a frame and stick it into the parent element, the scrollbar won't appear.
* So we fake a scrollbar in the wrapping div.
**/
biggestFrame: false,
bodyCache: null, /* Cache the body HTML in case we need to re-use it later */
flags: 0x1 | 0x2 | 0x4, /* Start with all flags set. */
/* constants */
FLAG_STRIP_UNLIKELYS: 0x1,
FLAG_WEIGHT_CLASSES: 0x2,
FLAG_CLEAN_CONDITIONALLY: 0x4,
maxPages: 30, /* The maximum number of pages to loop through before we call it quits and just show a link. */
parsedPages: {}, /* The list of pages we've parsed in this call of readability, for autopaging. As a key store for easier searching. */
pageETags: {}, /* A list of the ETag headers of pages we've parsed, in case they happen to match, we'll know it's a duplicate. */
/**
* All of the regular expressions in use within readability.
* Defined up here so we don't instantiate them repeatedly in loops.
**/
regexps: {
unlikelyCandidates: /combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup|tweet|twitter/i,
okMaybeItsACandidate: /and|article|body|column|main|shadow/i,
positive: /article|body|content|entry|hentry|main|page|pagination|post|text|blog|story/i,
negative: /combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget/i,
extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single/i,
divToPElements: /<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i,
replaceBrs: /(<br[^>]*>[ \n\r\t]*){2,}/gi,
replaceFonts: /<(\/?)font[^>]*>/gi,
trim: /^\s+|\s+$/g,
normalize: /\s{2,}/g,
killBreaks: /(<br\s*\/?>(\s| ?)*){1,}/g,
videos: /http:\/\/(www\.)?(youtube|vimeo)\.com/i,
skipFootnoteLink: /^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i,
nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, // Match: next, continue, >, >>, » but not >|, »| as those usually mean last.
prevLink: /(prev|earl|old|new|<|«)/i
},
/**
* Runs readability.
*
* Workflow:
* 1. Prep the document by removing script tags, css, etc.
* 2. Build readability's DOM tree.
* 3. Grab the article content from the current dom tree.
* 4. Replace the current DOM tree with the new one.
* 5. Read peacefully.
*
* @return void
**/
init: function() {
/* Before we do anything, remove all scripts that are not readability. */
window.onload = window.onunload = function() {};
readability.removeScripts(document);
if(document.body && !readability.bodyCache) {
readability.bodyCache = document.body.innerHTML;
}
/* Make sure this document is added to the list of parsed pages first, so we don't double up on the first page */
readability.parsedPages[window.location.href.replace(/\/$/, '')] = true;
/* Pull out any possible next page link first */
var nextPageLink = readability.findNextPageLink(document.body);
readability.prepDocument();
/* Build readability's DOM tree */
var overlay = document.createElement("DIV");
var innerDiv = document.createElement("DIV");
var articleTools = readability.getArticleTools();
var articleTitle = readability.getArticleTitle();
var articleContent = readability.grabArticle();
var articleFooter = readability.getArticleFooter();
if(!articleContent) {
articleContent = document.createElement("DIV");
articleContent.id = "readability-content";
articleContent.innerHTML = [
"<p>Sorry, readability was unable to parse this page for content. If you feel like it should have been able to, please <a href='http://code.google.com/p/arc90labs-readability/issues/entry'>let us know by submitting an issue.</a></p>",
(readability.frameHack ? "<p><strong>It appears this page uses frames.</strong> Unfortunately, browser security properties often cause Readability to fail on pages that include frames. You may want to try running readability itself on this source page: <a href='" + readability.biggestFrame.src + "'>" + readability.biggestFrame.src + "</a></p>" : ""),
"<p>Also, please note that Readability does not play very nicely with front pages. Readability is intended to work on articles with a sizable chunk of text that you'd like to read comfortably. If you're using Readability on a landing page (like nytimes.com for example), please click into an article first before using Readability.</p>"
].join('');
nextPageLink = null;
}
overlay.id = "readOverlay";
innerDiv.id = "readInner";
/* Apply user-selected styling */
readStyle = 'temp-style';
readMargin = 'temp-margin';
readSize = 'temp-readSize';
document.body.className = readStyle;
document.dir = readability.getSuggestedDirection(articleTitle.innerHTML);
if (readStyle === "style-athelas" || readStyle === "style-apertura"){
overlay.className = readStyle + " rdbTypekit";
}
else {
overlay.className = readStyle;
}
innerDiv.className = readMargin + " " + readSize;
if(typeof(readConvertLinksToFootnotes) !== 'undefined' && readConvertLinksToFootnotes === true) {
readability.convertLinksToFootnotes = true;
}
/* Glue the structure of our document together. */
innerDiv.appendChild( articleTitle );
innerDiv.appendChild( articleContent );
innerDiv.appendChild( articleFooter );
overlay.appendChild( articleTools );
overlay.appendChild( innerDiv );
/* Clear the old HTML, insert the new content. */
document.body.innerHTML = "";
document.body.insertBefore(overlay, document.body.firstChild);
document.body.removeAttribute('style');
/* Add the css */
chrome.storage.sync.get({
cssReadability: '',
}, function(items) {
if (items.cssReadability) {
// Apply custom style
document.querySelector('head').innerHTML = '<style>' + items.cssReadability + '</style>';
} else {
// Apply default style
var cssFile = chrome.extension.getURL("css/readability.css");
document.querySelector('head').innerHTML = '<link rel="stylesheet" type="text/css" href="' + cssFile + '" >';
}
});
if(readability.frameHack)
{
var readOverlay = document.getElementById('readOverlay');
readOverlay.style.height = '100%';
readOverlay.style.overflow = 'auto';
}
/**
* If someone tries to use Readability on a site's root page, give them a warning about usage.
**/
if((window.location.protocol + "//" + window.location.host + "/") === window.location.href)
{
articleContent.style.display = "none";
var rootWarning = document.createElement('p');
rootWarning.id = "readability-warning";
rootWarning.innerHTML = "<em>Readability</em> was intended for use on individual articles and not home pages. " +
"If you'd like to try rendering this page anyway, <a onClick='javascript:document.getElementById(\"readability-warning\").style.display=\"none\";document.getElementById(\"readability-content\").style.display=\"block\";'>click here</a> to continue.";
innerDiv.insertBefore( rootWarning, articleContent );
}
readability.postProcessContent(articleContent);
window.scrollTo(0, 0);
/* If we're using the Typekit library, select the font */
if (readStyle === "style-athelas" || readStyle === "style-apertura") {
readability.useRdbTypekit();
}
if (nextPageLink) {
/**
* Append any additional pages after a small timeout so that people
* can start reading without having to wait for this to finish processing.
**/
window.setTimeout(function() {
readability.appendNextPage(nextPageLink);
}, 500);
}
/** Smooth scrolling **/
document.onkeydown = function(e) {
var code = (window.event) ? event.keyCode : e.keyCode;
if (code === 16) {
readability.reversePageScroll = true;
return;
}
if (code === 32) {
readability.curScrollStep = 0;
var windowHeight = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);
if(readability.reversePageScroll) {
readability.scrollTo(readability.scrollTop(), readability.scrollTop() - (windowHeight - 50), 20, 10);
}
else {
readability.scrollTo(readability.scrollTop(), readability.scrollTop() + (windowHeight - 50), 20, 10);
}
return false;
}
};
document.onkeyup = function(e) {
var code = (window.event) ? event.keyCode : e.keyCode;
if (code === 16) {
readability.reversePageScroll = false;
return;
}
};
},
/**
* Run any post-process modifications to article content as necessary.
*
* @param Element
* @return void
**/
postProcessContent: function(articleContent) {
if(readability.convertLinksToFootnotes && !window.location.href.match(/wikipedia\.org/g)) {
readability.addFootnotes(articleContent);
}
readability.fixImageFloats(articleContent);
},
/**
* Some content ends up looking ugly if the image is too large to be floated.
* If the image is wider than a threshold (currently 55%), no longer float it,
* center it instead.
*
* @param Element
* @return void
**/
fixImageFloats: function (articleContent) {
var imageWidthThreshold = Math.min(articleContent.offsetWidth, 800) * 0.55,
images = articleContent.getElementsByTagName('img');
for(var i=0, il = images.length; i < il; i+=1) {
var image = images[i];
if(image.offsetWidth > imageWidthThreshold) {
image.className += " blockImage";
}
}
},
/**
* Get the article tools Element that has buttons like reload, print.
*
* @return void
**/
getArticleTools: function () {
var articleTools = document.createElement("DIV");
articleTools.id = "readTools";
articleTools.innerHTML =
"<a href='#' onclick='return window.location.reload()' title='Reload original page' id='reload-page'>Reload Original Page</a> – " +
"<a href='#' onclick='javascript:window.print();' title='Print page' id='print-page'>Print Page</a>";
return articleTools;
},
/**
* retuns the suggested direction of the string
*
* @return "rtl" || "ltr"
**/
getSuggestedDirection: function(text) {
function sanitizeText() {
return text.replace(/@\w+/, "");
}
function countMatches(match) {
var matches = text.match(new RegExp(match, "g"));
return matches !== null ? matches.length : 0;
}
function isRTL() {
var count_heb = countMatches("[\\u05B0-\\u05F4\\uFB1D-\\uFBF4]");
var count_arb = countMatches("[\\u060C-\\u06FE\\uFB50-\\uFEFC]");
// if 20% of chars are Hebrew or Arbic then direction is rtl
return (count_heb + count_arb) * 100 / text.length > 20;
}
text = sanitizeText(text);
return isRTL() ? "rtl" : "ltr";
},
/**
* Get the article title as an H1.
*
* @return void
**/
getArticleTitle: function () {
var curTitle = "",
origTitle = "";
try {
curTitle = origTitle = document.title;
if(typeof curTitle !== "string") { /* If they had an element with id "title" in their HTML */
curTitle = origTitle = readability.getInnerText(document.getElementsByTagName('title')[0]);
}
}
catch(e) {}
if(curTitle.match(/ [\|\-] /))
{
curTitle = origTitle.replace(/(.*)[\|\-] .*/gi,'$1');
if(curTitle.split(' ').length < 3) {
curTitle = origTitle.replace(/[^\|\-]*[\|\-](.*)/gi,'$1');
}
}
else if(curTitle.indexOf(': ') !== -1)
{
curTitle = origTitle.replace(/.*:(.*)/gi, '$1');
if(curTitle.split(' ').length < 3) {
curTitle = origTitle.replace(/[^:]*[:](.*)/gi,'$1');
}
}
else if(curTitle.length > 150 || curTitle.length < 15)
{
var hOnes = document.getElementsByTagName('h1');
if(hOnes.length === 1)
{
curTitle = readability.getInnerText(hOnes[0]);
}
}
curTitle = curTitle.replace( readability.regexps.trim, "" );
if(curTitle.split(' ').length <= 4) {
curTitle = origTitle;
}
var articleTitle = document.createElement("h1");
articleTitle.innerHTML = curTitle;
return articleTitle;
},
/**
* Get the footer with the readability mark etc.
*
* @return void
**/
getArticleFooter: function () {
var articleFooter = document.createElement("div");
articleFooter.id = "readFooter";
articleFooter.innerHTML = "<div id='rdb-footer-print'>Excerpted from <cite>" + document.title + "</cite><br><a href=\"" + window.location.href + "\">" + window.location.href + "</a></div>";
return articleFooter;
},
/**
* Prepare the HTML document for readability to scrape it.
* This includes things like stripping javascript, CSS, and handling terrible markup.
*
* @return void
**/
prepDocument: function () {
/**
* In some cases a body element can't be found (if the HTML is totally hosed for example)
* so we create a new body node and append it to the document.
*/
if(document.body === null)
{
var body = document.createElement("body");
try {
document.body = body;
}
catch(e) {
document.documentElement.appendChild(body);
dbg(e);
}
}
document.body.id = "readabilityBody";
var frames = document.getElementsByTagName('frame');
if(frames.length > 0)
{
var bestFrame = null;
var bestFrameSize = 0; /* The frame to try to run readability upon. Must be on same domain. */
var biggestFrameSize = 0; /* Used for the error message. Can be on any domain. */
for(var frameIndex = 0; frameIndex < frames.length; frameIndex+=1)
{
var frameSize = frames[frameIndex].offsetWidth + frames[frameIndex].offsetHeight;
var canAccessFrame = false;
try {
var frameBody = frames[frameIndex].contentWindow.document.body;
canAccessFrame = true;
}
catch(eFrames) {
dbg(eFrames);
}
if(frameSize > biggestFrameSize) {
biggestFrameSize = frameSize;
readability.biggestFrame = frames[frameIndex];
}
if(canAccessFrame && frameSize > bestFrameSize)
{
readability.frameHack = true;
bestFrame = frames[frameIndex];
bestFrameSize = frameSize;
}
}
if(bestFrame)
{
var newBody = document.createElement('body');
newBody.innerHTML = bestFrame.contentWindow.document.body.innerHTML;
newBody.style.overflow = 'scroll';
document.body = newBody;
var frameset = document.getElementsByTagName('frameset')[0];
if(frameset) {
frameset.parentNode.removeChild(frameset); }
}
}
/* Remove all stylesheets */
for (var k=0;k < document.styleSheets.length; k+=1) {
if (document.styleSheets[k].href !== null && document.styleSheets[k].href.lastIndexOf("readability") === -1) {
document.styleSheets[k].disabled = true;
}
}
/* Remove all style tags in head (not doing this on IE) - TODO: Why not? */
var styleTags = document.getElementsByTagName("style");
for (var st=0;st < styleTags.length; st+=1) {
styleTags[st].textContent = "";
}
/* Turn all double br's into p's */
/* Note, this is pretty costly as far as processing goes. Maybe optimize later. */
document.body.innerHTML = document.body.innerHTML.replace(readability.regexps.replaceBrs, '</p><p>').replace(readability.regexps.replaceFonts, '<$1span>');
},
/**
* For easier reading, convert this document to have footnotes at the bottom rather than inline links.
* @see http://www.roughtype.com/archives/2010/05/experiments_in.php
*
* @return void
**/
addFootnotes: function(articleContent) {
var footnotesWrapper = document.getElementById('readability-footnotes'),
articleFootnotes = document.getElementById('readability-footnotes-list');
if(!footnotesWrapper) {
footnotesWrapper = document.createElement("div");
footnotesWrapper.id = 'readability-footnotes';
footnotesWrapper.innerHTML = '<h3>References</h3>';
footnotesWrapper.style.display = 'none'; /* Until we know we have footnotes, don't show the references block. */
articleFootnotes = document.createElement('ol');
articleFootnotes.id = 'readability-footnotes-list';
footnotesWrapper.appendChild(articleFootnotes);
var readFooter = document.getElementById('readFooter');
if(readFooter) {
readFooter.parentNode.insertBefore(footnotesWrapper, readFooter);
}
}
var articleLinks = articleContent.getElementsByTagName('a');
var linkCount = articleFootnotes.getElementsByTagName('li').length;
for (var i = 0; i < articleLinks.length; i+=1)
{
var articleLink = articleLinks[i],
footnoteLink = articleLink.cloneNode(true),
refLink = document.createElement('a'),
footnote = document.createElement('li'),
linkDomain = footnoteLink.host ? footnoteLink.host : document.location.host,
linkText = readability.getInnerText(articleLink);
if(articleLink.className && articleLink.className.indexOf('readability-DoNotFootnote') !== -1 || linkText.match(readability.regexps.skipFootnoteLink)) {
continue;
}
linkCount+=1;
/** Add a superscript reference after the article link */
refLink.href = '#readabilityFootnoteLink-' + linkCount;
refLink.innerHTML = '<small><sup>[' + linkCount + ']</sup></small>';
refLink.className = 'readability-DoNotFootnote';
try { refLink.style.color = 'inherit'; } catch(e) {} /* IE7 doesn't like inherit. */
if(articleLink.parentNode.lastChild === articleLink) {
articleLink.parentNode.appendChild(refLink);
} else {
articleLink.parentNode.insertBefore(refLink, articleLink.nextSibling);
}
articleLink.name = 'readabilityLink-' + linkCount;
try { articleLink.style.color = 'inherit'; } catch(err) {} /* IE7 doesn't like inherit. */
footnote.innerHTML = "<small><sup><a href='#readabilityLink-" + linkCount + "' title='Jump to Link in Article'>^</a></sup></small> ";
footnoteLink.innerHTML = (footnoteLink.title ? footnoteLink.title : linkText);
footnoteLink.name = 'readabilityFootnoteLink-' + linkCount;
footnote.appendChild(footnoteLink);
footnote.innerHTML = footnote.innerHTML + "<small> (" + linkDomain + ")</small>";
articleFootnotes.appendChild(footnote);
}
if(linkCount > 0) {
footnotesWrapper.style.display = 'block';
}
},
useRdbTypekit: function () {
var rdbHead = document.getElementsByTagName('head')[0];
var rdbTKScript = document.createElement('script');
var rdbTKCode = null;
var rdbTKLink = document.createElement('a');
rdbTKLink.setAttribute('class','rdbTK-powered');
rdbTKLink.setAttribute('title','Fonts by Typekit');
rdbTKLink.innerHTML = "Fonts by <span class='rdbTK'>Typekit</span>";
if (readStyle === "style-athelas") {
rdbTKCode = "sxt6vzy";
dbg("Using Athelas Theme");
rdbTKLink.setAttribute('href','http://typekit.com/?utm_source=readability&utm_medium=affiliate&utm_campaign=athelas');
rdbTKLink.setAttribute('id','rdb-athelas');
document.getElementById("rdb-footer-right").appendChild(rdbTKLink);
}
if (readStyle === "style-apertura") {
rdbTKCode = "bae8ybu";
dbg("Using Inverse Theme");
rdbTKLink.setAttribute('href','http://typekit.com/?utm_source=readability&utm_medium=affiliate&utm_campaign=inverse');
rdbTKLink.setAttribute('id','rdb-inverse');
document.getElementById("rdb-footer-right").appendChild(rdbTKLink);
}
/**
* Setting new script tag attributes to pull Typekits libraries
**/
rdbTKScript.setAttribute('type','text/javascript');
rdbTKScript.setAttribute('src',"http://use.typekit.com/" + rdbTKCode + ".js");
rdbTKScript.setAttribute('charset','UTF-8');
rdbHead.appendChild(rdbTKScript);
/**
* In the future, maybe try using the following experimental Callback function?:
* http://gist.github.com/192350
* &
* http://getsatisfaction.com/typekit/topics/support_a_pre_and_post_load_callback_function
**/
var typekitLoader = function() {
dbg("Looking for Typekit.");
if(typeof Typekit !== "undefined") {
try {
dbg("Caught typekit");
Typekit.load();
clearInterval(window.typekitInterval);
} catch(e) {
dbg("Typekit error: " + e);
}
}
};
window.typekitInterval = window.setInterval(typekitLoader, 100);
},
/**
* Prepare the article node for display. Clean out any inline styles,
* iframes, forms, strip extraneous <p> tags, etc.
*
* @param Element
* @return void
**/
prepArticle: function (articleContent) {
readability.cleanStyles(articleContent);
readability.killBreaks(articleContent);
/* Clean out junk from the article content */
readability.cleanConditionally(articleContent, "form");
readability.clean(articleContent, "object");
readability.clean(articleContent, "h1");
/**
* If there is only one h2, they are probably using it
* as a header and not a subheader, so remove it since we already have a header.
***/
if(articleContent.getElementsByTagName('h2').length === 1) {
readability.clean(articleContent, "h2");
}
readability.clean(articleContent, "iframe");
readability.cleanHeaders(articleContent);
/* Do these last as the previous stuff may have removed junk that will affect these */
readability.cleanConditionally(articleContent, "table");
readability.cleanConditionally(articleContent, "ul");
readability.cleanConditionally(articleContent, "div");
/* Remove extra paragraphs */
var articleParagraphs = articleContent.getElementsByTagName('p');
for(var i = articleParagraphs.length-1; i >= 0; i-=1) {
var imgCount = articleParagraphs[i].getElementsByTagName('img').length;
var embedCount = articleParagraphs[i].getElementsByTagName('embed').length;
var objectCount = articleParagraphs[i].getElementsByTagName('object').length;
if(imgCount === 0 && embedCount === 0 && objectCount === 0 && readability.getInnerText(articleParagraphs[i], false) === '') {
articleParagraphs[i].parentNode.removeChild(articleParagraphs[i]);
}
}
try {
articleContent.innerHTML = articleContent.innerHTML.replace(/<br[^>]*>\s*<p/gi, '<p');
}
catch (e) {
dbg("Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring.: " + e);
}
},
/**
* Initialize a node with the readability object. Also checks the
* className/id for special names to add to its score.
*
* @param Element
* @return void
**/
initializeNode: function (node) {
node.readability = {"contentScore": 0};
switch(node.tagName) {
case 'DIV':
node.readability.contentScore += 5;
break;
case 'PRE':
case 'TD':
case 'BLOCKQUOTE':
node.readability.contentScore += 3;
break;
case 'ADDRESS':
case 'OL':
case 'UL':
case 'DL':
case 'DD':
case 'DT':
case 'LI':
case 'FORM':
node.readability.contentScore -= 3;
break;
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
case 'TH':
node.readability.contentScore -= 5;
break;
}
node.readability.contentScore += readability.getClassWeight(node);
},
/***
* grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
* most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
*
* @param page a document to run upon. Needs to be a full document, complete with body.
* @return Element
**/
grabArticle: function (page) {
var stripUnlikelyCandidates = readability.flagIsActive(readability.FLAG_STRIP_UNLIKELYS),
isPaging = (page !== null) ? true: false;
page = page ? page : document.body;
var pageCacheHtml = page.innerHTML;
var allElements = page.getElementsByTagName('*');
/**
* First, node prepping. Trash nodes that look cruddy (like ones with the class name "comment", etc), and turn divs
* into P tags where they have been used inappropriately (as in, where they contain no other block level elements.)
*
* Note: Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
* TODO: Shouldn't this be a reverse traversal?
**/
var node = null;
var nodesToScore = [];
for(var nodeIndex = 0; (node = allElements[nodeIndex]); nodeIndex+=1) {
/* Remove unlikely candidates */
if (stripUnlikelyCandidates) {
var unlikelyMatchString = node.className + node.id;
if (
(
unlikelyMatchString.search(readability.regexps.unlikelyCandidates) !== -1 &&
unlikelyMatchString.search(readability.regexps.okMaybeItsACandidate) === -1 &&
node.tagName !== "BODY"
)
)
{
dbg("Removing unlikely candidate - " + unlikelyMatchString);
node.parentNode.removeChild(node);
nodeIndex-=1;
continue;
}
}
if (node.tagName === "P" || node.tagName === "TD" || node.tagName === "PRE") {
nodesToScore[nodesToScore.length] = node;
}
/* Turn all divs that don't have children block level elements into p's */
if (node.tagName === "DIV") {
if (node.innerHTML.search(readability.regexps.divToPElements) === -1) {
var newNode = document.createElement('p');
try {
newNode.innerHTML = node.innerHTML;
node.parentNode.replaceChild(newNode, node);
nodeIndex-=1;
nodesToScore[nodesToScore.length] = node;
}
catch(e) {
dbg("Could not alter div to p, probably an IE restriction, reverting back to div.: " + e);
}
}
else
{
/* EXPERIMENTAL */
for(var i = 0, il = node.childNodes.length; i < il; i+=1) {
var childNode = node.childNodes[i];
if(childNode.nodeType === 3) { // Node.TEXT_NODE
var p = document.createElement('p');
p.innerHTML = childNode.nodeValue;
p.style.display = 'inline';
p.className = 'readability-styled';
childNode.parentNode.replaceChild(p, childNode);
}
}
}
}
}
/**
* Loop through all paragraphs, and assign a score to them based on how content-y they look.
* Then add their score to their parent node.
*
* A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
**/
var candidates = [];
for (var pt=0; pt < nodesToScore.length; pt+=1) {
var parentNode = nodesToScore[pt].parentNode;
var grandParentNode = parentNode ? parentNode.parentNode : null;
var innerText = readability.getInnerText(nodesToScore[pt]);
if(!parentNode || typeof(parentNode.tagName) === 'undefined') {
continue;
}
/* If this paragraph is less than 25 characters, don't even count it. */
if(innerText.length < 25) {
continue; }
/* Initialize readability data for the parent. */
if(typeof parentNode.readability === 'undefined') {
readability.initializeNode(parentNode);
candidates.push(parentNode);
}
/* Initialize readability data for the grandparent. */
if(grandParentNode && typeof(grandParentNode.readability) === 'undefined' && typeof(grandParentNode.tagName) !== 'undefined') {
readability.initializeNode(grandParentNode);
candidates.push(grandParentNode);
}
var contentScore = 0;
/* Add a point for the paragraph itself as a base. */
contentScore+=1;
/* Add points for any commas within this paragraph */
contentScore += innerText.split(',').length;
/* For every 100 characters in this paragraph, add another point. Up to 3 points. */
contentScore += Math.min(Math.floor(innerText.length / 100), 3);
/* Add the score to the parent. The grandparent gets half. */
parentNode.readability.contentScore += contentScore;
if(grandParentNode) {
grandParentNode.readability.contentScore += contentScore/2;
}
}
/**
* After we've calculated scores, loop through all of the possible candidate nodes we found
* and find the one with the highest score.
**/
var topCandidate = null;
for(var c=0, cl=candidates.length; c < cl; c+=1)
{
/**
* Scale the final candidates score based on link density. Good content should have a
* relatively small link density (5% or less) and be mostly unaffected by this operation.
**/
candidates[c].readability.contentScore = candidates[c].readability.contentScore * (1-readability.getLinkDensity(candidates[c]));
dbg('Candidate: ' + candidates[c] + " (" + candidates[c].className + ":" + candidates[c].id + ") with score " + candidates[c].readability.contentScore);
if(!topCandidate || candidates[c].readability.contentScore > topCandidate.readability.contentScore) {
topCandidate = candidates[c]; }
}
/**
* If we still have no top candidate, just use the body as a last resort.
* We also have to copy the body node so it is something we can modify.
**/
if (topCandidate === null || topCandidate.tagName === "body")
{
topCandidate = document.createElement("div");
topCandidate.innerHTML = page.innerHTML;
page.innerHTML = "";
page.appendChild(topCandidate);
readability.initializeNode(topCandidate);
}
/**
* Now that we have the top candidate, look through its siblings for content that might also be related.
* Things like preambles, content split by ads that we removed, etc.
**/
var articleContent = document.createElement("div");
if (isPaging) {
articleContent.id = "readability-content";
}
var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2);
var siblingNodes = topCandidate.parentNode.childNodes;
for(var s=0, sl=siblingNodes.length; s < sl; s+=1) {
var siblingNode = siblingNodes[s];
var append = false;
/**
* Fix for odd IE7 Crash where siblingNode does not exist even though this should be a live nodeList.
* Example of error visible here: http://www.esquire.com/features/honesty0707
**/
if(!siblingNode) {
continue;
}
dbg("Looking at sibling node: " + siblingNode + " (" + siblingNode.className + ":" + siblingNode.id + ")" + ((typeof siblingNode.readability !== 'undefined') ? (" with score " + siblingNode.readability.contentScore) : ''));
dbg("Sibling has score " + (siblingNode.readability ? siblingNode.readability.contentScore : 'Unknown'));
if(siblingNode === topCandidate)
{
append = true;
}
var contentBonus = 0;
/* Give a bonus if sibling nodes and top candidates have the example same classname */
if(siblingNode.className === topCandidate.className && topCandidate.className !== "") {
contentBonus += topCandidate.readability.contentScore * 0.2;
}
if(typeof siblingNode.readability !== 'undefined' && (siblingNode.readability.contentScore+contentBonus) >= siblingScoreThreshold)
{
append = true;
}
if(siblingNode.nodeName === "P") {
var linkDensity = readability.getLinkDensity(siblingNode);
var nodeContent = readability.getInnerText(siblingNode);
var nodeLength = nodeContent.length;
if(nodeLength > 80 && linkDensity < 0.25)
{
append = true;
}
else if(nodeLength < 80 && linkDensity === 0 && nodeContent.search(/\.( |$)/) !== -1)
{
append = true;
}
}
if(append) {
dbg("Appending node: " + siblingNode);
var nodeToAppend = null;
if(siblingNode.nodeName !== "DIV" && siblingNode.nodeName !== "P") {
/* We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident. */
dbg("Altering siblingNode of " + siblingNode.nodeName + ' to div.');
nodeToAppend = document.createElement("div");
try {
nodeToAppend.id = siblingNode.id;
nodeToAppend.innerHTML = siblingNode.innerHTML;
}
catch(er) {
dbg("Could not alter siblingNode to div, probably an IE restriction, reverting back to original.");
nodeToAppend = siblingNode;
s-=1;
sl-=1;
}
} else {
nodeToAppend = siblingNode;
s-=1;
sl-=1;
}
/* To ensure a node does not interfere with readability styles, remove its classnames */
nodeToAppend.className = "";
/* Append sibling and subtract from our list because it removes the node when you append to another node */
articleContent.appendChild(nodeToAppend);
}
}
/**
* So we have all of the content that we need. Now we clean it up for presentation.
**/
readability.prepArticle(articleContent);
if (readability.curPageNum === 1) {
articleContent.innerHTML = '<div id="readability-page-1" class="page">' + articleContent.innerHTML + '</div>';
}
/**
* Now that we've gone through the full algorithm, check to see if we got any meaningful content.
* If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher
* likelihood of finding the content, and the sieve approach gives us a higher likelihood of
* finding the -right- content.
**/
if(readability.getInnerText(articleContent, false).length < 250) {
page.innerHTML = pageCacheHtml;
if (readability.flagIsActive(readability.FLAG_STRIP_UNLIKELYS)) {
readability.removeFlag(readability.FLAG_STRIP_UNLIKELYS);
return readability.grabArticle(page);
}
else if (readability.flagIsActive(readability.FLAG_WEIGHT_CLASSES)) {
readability.removeFlag(readability.FLAG_WEIGHT_CLASSES);
return readability.grabArticle(page);
}
else if (readability.flagIsActive(readability.FLAG_CLEAN_CONDITIONALLY)) {
readability.removeFlag(readability.FLAG_CLEAN_CONDITIONALLY);
return readability.grabArticle(page);
} else {
return null;
}
}
return articleContent;
},
/**
* Removes script tags from the document.
*
* @param Element
**/
removeScripts: function (doc) {
var scripts = doc.getElementsByTagName('script');
for(var i = scripts.length-1; i >= 0; i-=1)
{