textextractor.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. // Copyright 2017 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Contains utility methods to extract text content from HTML.
  16. * @supported IE 10+, Chrome 26+, Firefox 22+, Safari 7.1+, Opera 15+
  17. */
  18. goog.provide('goog.html.textExtractor');
  19. goog.require('goog.array');
  20. goog.require('goog.dom.TagName');
  21. goog.require('goog.html.sanitizer.HtmlSanitizer');
  22. goog.require('goog.object');
  23. goog.require('goog.userAgent');
  24. /**
  25. * Safely extracts text from an untrusted HTML string using the HtmlSanitizer.
  26. * Compared to goog.html.utils.stripHtmlTags, it tries to be smarter about
  27. * printing newlines between blocks and leave out textual content that would not
  28. * be displayed to the user (such as SCRIPT and STYLE tags).
  29. * @param {string} html The untrusted HTML string.
  30. * @return {string}
  31. */
  32. // TODO(pelizzi): consider an optional bool parameter to also extract the text
  33. // content of alt attributes and such.
  34. goog.html.textExtractor.extractTextContent = function(html) {
  35. if (!goog.html.textExtractor.isSupported()) {
  36. return '';
  37. }
  38. // Disable all attributes except style to protect against DOM clobbering.
  39. var sanitizer = new goog.html.sanitizer.HtmlSanitizer.Builder()
  40. .onlyAllowAttributes(['style'])
  41. .allowCssStyles()
  42. .build();
  43. // The default policy of the sanitizer strips the content of tags such as
  44. // SCRIPT and STYLE, whose non-textual content would otherwise end up in the
  45. // extracted text.
  46. var sanitizedNodes = sanitizer.sanitizeToDomNode(html);
  47. // textContent and innerText do not handle spacing between block elements
  48. // properly. We need to reimplement a similar algorithm ourselves and account
  49. // for spacing between block elements.
  50. return goog.html.textExtractor.extractTextContentFromNode_(sanitizedNodes)
  51. .trim();
  52. };
  53. /**
  54. * Recursively extract text from the supplied DOM node and its descendants.
  55. * @param {!Node} node
  56. * @return {string}
  57. * @private
  58. */
  59. goog.html.textExtractor.extractTextContentFromNode_ = function(node) {
  60. switch (node.nodeType) {
  61. case Node.ELEMENT_NODE:
  62. var element = /** @type {!Element} */ (node);
  63. if (element.tagName == goog.dom.TagName.BR) {
  64. return '\n';
  65. }
  66. var result = goog.array
  67. .map(
  68. node.childNodes,
  69. goog.html.textExtractor.extractTextContentFromNode_)
  70. .join('');
  71. if (goog.html.textExtractor.isBlockElement_(element)) {
  72. result = '\n' + result + '\n';
  73. }
  74. return result;
  75. case Node.TEXT_NODE:
  76. return node.nodeValue.replace(/\s+/g, ' ').trim();
  77. default:
  78. return '';
  79. }
  80. };
  81. /**
  82. * A set of block elements.
  83. * @private @const {!Object<!goog.dom.TagName, boolean>}
  84. */
  85. goog.html.textExtractor.BLOCK_ELEMENTS_ = goog.object.createSet(
  86. goog.dom.TagName.ADDRESS, goog.dom.TagName.BLOCKQUOTE,
  87. goog.dom.TagName.CENTER, goog.dom.TagName.DIV, goog.dom.TagName.DL,
  88. goog.dom.TagName.FIELDSET, goog.dom.TagName.FORM, goog.dom.TagName.H1,
  89. goog.dom.TagName.H2, goog.dom.TagName.H3, goog.dom.TagName.H4,
  90. goog.dom.TagName.H5, goog.dom.TagName.H6, goog.dom.TagName.HR,
  91. goog.dom.TagName.OL, goog.dom.TagName.P, goog.dom.TagName.PRE,
  92. goog.dom.TagName.TABLE, goog.dom.TagName.UL);
  93. /**
  94. * Returns true whether this is a block element, i.e. the browser would visually
  95. * separate the text content from the text content of the previous node.
  96. * @param {!Element} element
  97. * @return {boolean}
  98. * @private
  99. */
  100. goog.html.textExtractor.isBlockElement_ = function(element) {
  101. return element.style.display == 'block' ||
  102. goog.html.textExtractor.BLOCK_ELEMENTS_.hasOwnProperty(element.tagName);
  103. };
  104. /**
  105. * Whether the browser supports the text extractor. The extractor depends on the
  106. * HTML Sanitizer, which only supports IE starting from version 10.
  107. * Visible for testing.
  108. * @return {boolean}
  109. * @package
  110. */
  111. goog.html.textExtractor.isSupported = function() {
  112. return !goog.userAgent.IE || goog.userAgent.isVersionOrHigher(10);
  113. };