angular-sanitize.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /*
  2. The MIT License
  3. Copyright (c) 2010-2015 Google, Inc. http://angularjs.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /**
  21. * @license AngularJS v1.3.8
  22. * (c) 2010-2014 Google, Inc. http://angularjs.org
  23. * License: MIT
  24. */
  25. (function(window, angular, undefined) {'use strict';
  26. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  27. /**
  28. * @ngdoc module
  29. * @name ngSanitize
  30. * @description
  31. *
  32. * # ngSanitize
  33. *
  34. * The `ngSanitize` module provides functionality to sanitize HTML.
  35. *
  36. *
  37. * <div doc-module-components="ngSanitize"></div>
  38. *
  39. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  40. */
  41. /*
  42. * HTML Parser By Misko Hevery (misko@hevery.com)
  43. * based on: HTML Parser By John Resig (ejohn.org)
  44. * Original code by Erik Arvidsson, Mozilla Public License
  45. * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
  46. *
  47. * // Use like so:
  48. * htmlParser(htmlString, {
  49. * start: function(tag, attrs, unary) {},
  50. * end: function(tag) {},
  51. * chars: function(text) {},
  52. * comment: function(text) {}
  53. * });
  54. *
  55. */
  56. /**
  57. * @ngdoc service
  58. * @name $sanitize
  59. * @kind function
  60. *
  61. * @description
  62. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  63. * then serialized back to properly escaped html string. This means that no unsafe input can make
  64. * it into the returned string, however, since our parser is more strict than a typical browser
  65. * parser, it's possible that some obscure input, which would be recognized as valid HTML by a
  66. * browser, won't make it through the sanitizer. The input may also contain SVG markup.
  67. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and
  68. * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.
  69. *
  70. * @param {string} html HTML input.
  71. * @returns {string} Sanitized HTML.
  72. *
  73. * @example
  74. <example module="sanitizeExample" deps="angular-sanitize.js">
  75. <file name="index.html">
  76. <script>
  77. angular.module('sanitizeExample', ['ngSanitize'])
  78. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  79. $scope.snippet =
  80. '<p style="color:blue">an html\n' +
  81. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  82. 'snippet</p>';
  83. $scope.deliberatelyTrustDangerousSnippet = function() {
  84. return $sce.trustAsHtml($scope.snippet);
  85. };
  86. }]);
  87. </script>
  88. <div ng-controller="ExampleController">
  89. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  90. <table>
  91. <tr>
  92. <td>Directive</td>
  93. <td>How</td>
  94. <td>Source</td>
  95. <td>Rendered</td>
  96. </tr>
  97. <tr id="bind-html-with-sanitize">
  98. <td>ng-bind-html</td>
  99. <td>Automatically uses $sanitize</td>
  100. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  101. <td><div ng-bind-html="snippet"></div></td>
  102. </tr>
  103. <tr id="bind-html-with-trust">
  104. <td>ng-bind-html</td>
  105. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  106. <td>
  107. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  108. &lt;/div&gt;</pre>
  109. </td>
  110. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  111. </tr>
  112. <tr id="bind-default">
  113. <td>ng-bind</td>
  114. <td>Automatically escapes</td>
  115. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  116. <td><div ng-bind="snippet"></div></td>
  117. </tr>
  118. </table>
  119. </div>
  120. </file>
  121. <file name="protractor.js" type="protractor">
  122. it('should sanitize the html snippet by default', function() {
  123. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  124. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  125. });
  126. it('should inline raw snippet if bound to a trusted value', function() {
  127. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  128. toBe("<p style=\"color:blue\">an html\n" +
  129. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  130. "snippet</p>");
  131. });
  132. it('should escape snippet without any filter', function() {
  133. expect(element(by.css('#bind-default div')).getInnerHtml()).
  134. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  135. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  136. "snippet&lt;/p&gt;");
  137. });
  138. it('should update', function() {
  139. element(by.model('snippet')).clear();
  140. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  141. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  142. toBe('new <b>text</b>');
  143. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  144. 'new <b onclick="alert(1)">text</b>');
  145. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  146. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  147. });
  148. </file>
  149. </example>
  150. */
  151. function $SanitizeProvider() {
  152. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  153. return function(html) {
  154. var buf = [];
  155. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  156. return !/^unsafe/.test($$sanitizeUri(uri, isImage));
  157. }));
  158. return buf.join('');
  159. };
  160. }];
  161. }
  162. function sanitizeText(chars) {
  163. var buf = [];
  164. var writer = htmlSanitizeWriter(buf, angular.noop);
  165. writer.chars(chars);
  166. return buf.join('');
  167. }
  168. // Regular Expressions for parsing tags and attributes
  169. var START_TAG_REGEXP =
  170. /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
  171. END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
  172. ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
  173. BEGIN_TAG_REGEXP = /^</,
  174. BEGING_END_TAGE_REGEXP = /^<\//,
  175. COMMENT_REGEXP = /<!--(.*?)-->/g,
  176. DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,
  177. CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
  178. SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  179. // Match everything outside of normal chars and " (quote character)
  180. NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
  181. // Good source of info about elements and attributes
  182. // http://dev.w3.org/html5/spec/Overview.html#semantics
  183. // http://simon.html5.org/html-elements
  184. // Safe Void Elements - HTML5
  185. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  186. var voidElements = makeMap("area,br,col,hr,img,wbr");
  187. // Elements that you can, intentionally, leave open (and which close themselves)
  188. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  189. var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  190. optionalEndTagInlineElements = makeMap("rp,rt"),
  191. optionalEndTagElements = angular.extend({},
  192. optionalEndTagInlineElements,
  193. optionalEndTagBlockElements);
  194. // Safe Block Elements - HTML5
  195. var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
  196. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  197. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
  198. // Inline Elements - HTML5
  199. var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
  200. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  201. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  202. // SVG Elements
  203. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  204. var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
  205. "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
  206. "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
  207. "stop,svg,switch,text,title,tspan,use");
  208. // Special Elements (can contain anything)
  209. var specialElements = makeMap("script,style");
  210. var validElements = angular.extend({},
  211. voidElements,
  212. blockElements,
  213. inlineElements,
  214. optionalEndTagElements,
  215. svgElements);
  216. //Attributes that have href and hence need to be sanitized
  217. var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
  218. var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  219. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  220. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  221. 'scope,scrolling,shape,size,span,start,summary,target,title,type,' +
  222. 'valign,value,vspace,width');
  223. // SVG attributes (without "id" and "name" attributes)
  224. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  225. var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  226. 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
  227. 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
  228. 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
  229. 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
  230. 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
  231. 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
  232. 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
  233. 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
  234. 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
  235. 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
  236. 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
  237. 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
  238. 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
  239. 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
  240. 'zoomAndPan');
  241. var validAttrs = angular.extend({},
  242. uriAttrs,
  243. svgAttrs,
  244. htmlAttrs);
  245. function makeMap(str) {
  246. var obj = {}, items = str.split(','), i;
  247. for (i = 0; i < items.length; i++) obj[items[i]] = true;
  248. return obj;
  249. }
  250. /**
  251. * @example
  252. * htmlParser(htmlString, {
  253. * start: function(tag, attrs, unary) {},
  254. * end: function(tag) {},
  255. * chars: function(text) {},
  256. * comment: function(text) {}
  257. * });
  258. *
  259. * @param {string} html string
  260. * @param {object} handler
  261. */
  262. function htmlParser(html, handler) {
  263. if (typeof html !== 'string') {
  264. if (html === null || typeof html === 'undefined') {
  265. html = '';
  266. } else {
  267. html = '' + html;
  268. }
  269. }
  270. var index, chars, match, stack = [], last = html, text;
  271. stack.last = function() { return stack[ stack.length - 1 ]; };
  272. while (html) {
  273. text = '';
  274. chars = true;
  275. // Make sure we're not in a script or style element
  276. if (!stack.last() || !specialElements[ stack.last() ]) {
  277. // Comment
  278. if (html.indexOf("<!--") === 0) {
  279. // comments containing -- are not allowed unless they terminate the comment
  280. index = html.indexOf("--", 4);
  281. if (index >= 0 && html.lastIndexOf("-->", index) === index) {
  282. if (handler.comment) handler.comment(html.substring(4, index));
  283. html = html.substring(index + 3);
  284. chars = false;
  285. }
  286. // DOCTYPE
  287. } else if (DOCTYPE_REGEXP.test(html)) {
  288. match = html.match(DOCTYPE_REGEXP);
  289. if (match) {
  290. html = html.replace(match[0], '');
  291. chars = false;
  292. }
  293. // end tag
  294. } else if (BEGING_END_TAGE_REGEXP.test(html)) {
  295. match = html.match(END_TAG_REGEXP);
  296. if (match) {
  297. html = html.substring(match[0].length);
  298. match[0].replace(END_TAG_REGEXP, parseEndTag);
  299. chars = false;
  300. }
  301. // start tag
  302. } else if (BEGIN_TAG_REGEXP.test(html)) {
  303. match = html.match(START_TAG_REGEXP);
  304. if (match) {
  305. // We only have a valid start-tag if there is a '>'.
  306. if (match[4]) {
  307. html = html.substring(match[0].length);
  308. match[0].replace(START_TAG_REGEXP, parseStartTag);
  309. }
  310. chars = false;
  311. } else {
  312. // no ending tag found --- this piece should be encoded as an entity.
  313. text += '<';
  314. html = html.substring(1);
  315. }
  316. }
  317. if (chars) {
  318. index = html.indexOf("<");
  319. text += index < 0 ? html : html.substring(0, index);
  320. html = index < 0 ? "" : html.substring(index);
  321. if (handler.chars) handler.chars(decodeEntities(text));
  322. }
  323. } else {
  324. html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
  325. function(all, text) {
  326. text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
  327. if (handler.chars) handler.chars(decodeEntities(text));
  328. return "";
  329. });
  330. parseEndTag("", stack.last());
  331. }
  332. if (html == last) {
  333. throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
  334. "of html: {0}", html);
  335. }
  336. last = html;
  337. }
  338. // Clean up any remaining tags
  339. parseEndTag();
  340. function parseStartTag(tag, tagName, rest, unary) {
  341. tagName = angular.lowercase(tagName);
  342. if (blockElements[ tagName ]) {
  343. while (stack.last() && inlineElements[ stack.last() ]) {
  344. parseEndTag("", stack.last());
  345. }
  346. }
  347. if (optionalEndTagElements[ tagName ] && stack.last() == tagName) {
  348. parseEndTag("", tagName);
  349. }
  350. unary = voidElements[ tagName ] || !!unary;
  351. if (!unary)
  352. stack.push(tagName);
  353. var attrs = {};
  354. rest.replace(ATTR_REGEXP,
  355. function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
  356. var value = doubleQuotedValue
  357. || singleQuotedValue
  358. || unquotedValue
  359. || '';
  360. attrs[name] = decodeEntities(value);
  361. });
  362. if (handler.start) handler.start(tagName, attrs, unary);
  363. }
  364. function parseEndTag(tag, tagName) {
  365. var pos = 0, i;
  366. tagName = angular.lowercase(tagName);
  367. if (tagName)
  368. // Find the closest opened tag of the same type
  369. for (pos = stack.length - 1; pos >= 0; pos--)
  370. if (stack[ pos ] == tagName)
  371. break;
  372. if (pos >= 0) {
  373. // Close all the open elements, up the stack
  374. for (i = stack.length - 1; i >= pos; i--)
  375. if (handler.end) handler.end(stack[ i ]);
  376. // Remove the open elements from the stack
  377. stack.length = pos;
  378. }
  379. }
  380. }
  381. var hiddenPre=document.createElement("pre");
  382. var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
  383. /**
  384. * decodes all entities into regular string
  385. * @param value
  386. * @returns {string} A string with decoded entities.
  387. */
  388. function decodeEntities(value) {
  389. if (!value) { return ''; }
  390. // Note: IE8 does not preserve spaces at the start/end of innerHTML
  391. // so we must capture them and reattach them afterward
  392. var parts = spaceRe.exec(value);
  393. var spaceBefore = parts[1];
  394. var spaceAfter = parts[3];
  395. var content = parts[2];
  396. if (content) {
  397. hiddenPre.innerHTML=content.replace(/</g,"&lt;");
  398. // innerText depends on styling as it doesn't display hidden elements.
  399. // Therefore, it's better to use textContent not to cause unnecessary
  400. // reflows. However, IE<9 don't support textContent so the innerText
  401. // fallback is necessary.
  402. content = 'textContent' in hiddenPre ?
  403. hiddenPre.textContent : hiddenPre.innerText;
  404. }
  405. return spaceBefore + content + spaceAfter;
  406. }
  407. /**
  408. * Escapes all potentially dangerous characters, so that the
  409. * resulting string can be safely inserted into attribute or
  410. * element text.
  411. * @param value
  412. * @returns {string} escaped text
  413. */
  414. function encodeEntities(value) {
  415. return value.
  416. replace(/&/g, '&amp;').
  417. replace(SURROGATE_PAIR_REGEXP, function(value) {
  418. var hi = value.charCodeAt(0);
  419. var low = value.charCodeAt(1);
  420. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  421. }).
  422. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  423. return '&#' + value.charCodeAt(0) + ';';
  424. }).
  425. replace(/</g, '&lt;').
  426. replace(/>/g, '&gt;');
  427. }
  428. /**
  429. * create an HTML/XML writer which writes to buffer
  430. * @param {Array} buf use buf.jain('') to get out sanitized html string
  431. * @returns {object} in the form of {
  432. * start: function(tag, attrs, unary) {},
  433. * end: function(tag) {},
  434. * chars: function(text) {},
  435. * comment: function(text) {}
  436. * }
  437. */
  438. function htmlSanitizeWriter(buf, uriValidator) {
  439. var ignore = false;
  440. var out = angular.bind(buf, buf.push);
  441. return {
  442. start: function(tag, attrs, unary) {
  443. tag = angular.lowercase(tag);
  444. if (!ignore && specialElements[tag]) {
  445. ignore = tag;
  446. }
  447. if (!ignore && validElements[tag] === true) {
  448. out('<');
  449. out(tag);
  450. angular.forEach(attrs, function(value, key) {
  451. var lkey=angular.lowercase(key);
  452. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  453. if (validAttrs[lkey] === true &&
  454. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  455. out(' ');
  456. out(key);
  457. out('="');
  458. out(encodeEntities(value));
  459. out('"');
  460. }
  461. });
  462. out(unary ? '/>' : '>');
  463. }
  464. },
  465. end: function(tag) {
  466. tag = angular.lowercase(tag);
  467. if (!ignore && validElements[tag] === true) {
  468. out('</');
  469. out(tag);
  470. out('>');
  471. }
  472. if (tag == ignore) {
  473. ignore = false;
  474. }
  475. },
  476. chars: function(chars) {
  477. if (!ignore) {
  478. out(encodeEntities(chars));
  479. }
  480. }
  481. };
  482. }
  483. // define ngSanitize module and register $sanitize service
  484. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  485. /* global sanitizeText: false */
  486. /**
  487. * @ngdoc filter
  488. * @name linky
  489. * @kind function
  490. *
  491. * @description
  492. * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
  493. * plain email address links.
  494. *
  495. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  496. *
  497. * @param {string} text Input text.
  498. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
  499. * @returns {string} Html-linkified text.
  500. *
  501. * @usage
  502. <span ng-bind-html="linky_expression | linky"></span>
  503. *
  504. * @example
  505. <example module="linkyExample" deps="angular-sanitize.js">
  506. <file name="index.html">
  507. <script>
  508. angular.module('linkyExample', ['ngSanitize'])
  509. .controller('ExampleController', ['$scope', function($scope) {
  510. $scope.snippet =
  511. 'Pretty text with some links:\n'+
  512. 'http://angularjs.org/,\n'+
  513. 'mailto:us@somewhere.org,\n'+
  514. 'another@somewhere.org,\n'+
  515. 'and one more: ftp://127.0.0.1/.';
  516. $scope.snippetWithTarget = 'http://angularjs.org/';
  517. }]);
  518. </script>
  519. <div ng-controller="ExampleController">
  520. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  521. <table>
  522. <tr>
  523. <td>Filter</td>
  524. <td>Source</td>
  525. <td>Rendered</td>
  526. </tr>
  527. <tr id="linky-filter">
  528. <td>linky filter</td>
  529. <td>
  530. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  531. </td>
  532. <td>
  533. <div ng-bind-html="snippet | linky"></div>
  534. </td>
  535. </tr>
  536. <tr id="linky-target">
  537. <td>linky target</td>
  538. <td>
  539. <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  540. </td>
  541. <td>
  542. <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
  543. </td>
  544. </tr>
  545. <tr id="escaped-html">
  546. <td>no filter</td>
  547. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  548. <td><div ng-bind="snippet"></div></td>
  549. </tr>
  550. </table>
  551. </file>
  552. <file name="protractor.js" type="protractor">
  553. it('should linkify the snippet with urls', function() {
  554. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  555. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  556. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  557. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  558. });
  559. it('should not linkify snippet without the linky filter', function() {
  560. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  561. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  562. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  563. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  564. });
  565. it('should update', function() {
  566. element(by.model('snippet')).clear();
  567. element(by.model('snippet')).sendKeys('new http://link.');
  568. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  569. toBe('new http://link.');
  570. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  571. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  572. .toBe('new http://link.');
  573. });
  574. it('should work with the target property', function() {
  575. expect(element(by.id('linky-target')).
  576. element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
  577. toBe('http://angularjs.org/');
  578. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  579. });
  580. </file>
  581. </example>
  582. */
  583. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  584. var LINKY_URL_REGEXP =
  585. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/,
  586. MAILTO_REGEXP = /^mailto:/;
  587. return function(text, target) {
  588. if (!text) return text;
  589. var match;
  590. var raw = text;
  591. var html = [];
  592. var url;
  593. var i;
  594. while ((match = raw.match(LINKY_URL_REGEXP))) {
  595. // We can not end in these as they are sometimes found at the end of the sentence
  596. url = match[0];
  597. // if we did not match ftp/http/www/mailto then assume mailto
  598. if (!match[2] && !match[4]) {
  599. url = (match[3] ? 'http://' : 'mailto:') + url;
  600. }
  601. i = match.index;
  602. addText(raw.substr(0, i));
  603. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  604. raw = raw.substring(i + match[0].length);
  605. }
  606. addText(raw);
  607. return $sanitize(html.join(''));
  608. function addText(text) {
  609. if (!text) {
  610. return;
  611. }
  612. html.push(sanitizeText(text));
  613. }
  614. function addLink(url, text) {
  615. html.push('<a ');
  616. if (angular.isDefined(target)) {
  617. html.push('target="',
  618. target,
  619. '" ');
  620. }
  621. html.push('href="',
  622. url.replace(/"/g, '&quot;'),
  623. '">');
  624. addText(text);
  625. html.push('</a>');
  626. }
  627. };
  628. }]);
  629. })(window, window.angular);