angular-sanitize.js 24 KB

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