angular-sanitize.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. /**
  2. * @license AngularJS v1.3.15
  3. * (c) 2010-2014 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. var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," +
  196. "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," +
  197. "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," +
  198. "stop,svg,switch,text,title,tspan,use");
  199. // Special Elements (can contain anything)
  200. var specialElements = makeMap("script,style");
  201. var validElements = angular.extend({},
  202. voidElements,
  203. blockElements,
  204. inlineElements,
  205. optionalEndTagElements,
  206. svgElements);
  207. //Attributes that have href and hence need to be sanitized
  208. var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href");
  209. var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  210. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  211. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  212. 'scope,scrolling,shape,size,span,start,summary,target,title,type,' +
  213. 'valign,value,vspace,width');
  214. // SVG attributes (without "id" and "name" attributes)
  215. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  216. var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  217. 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +
  218. 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +
  219. 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +
  220. 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +
  221. 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +
  222. 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +
  223. 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +
  224. 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +
  225. 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +
  226. 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +
  227. 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +
  228. 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +
  229. 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +
  230. 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +
  231. 'zoomAndPan');
  232. var validAttrs = angular.extend({},
  233. uriAttrs,
  234. svgAttrs,
  235. htmlAttrs);
  236. function makeMap(str) {
  237. var obj = {}, items = str.split(','), i;
  238. for (i = 0; i < items.length; i++) obj[items[i]] = true;
  239. return obj;
  240. }
  241. /**
  242. * @example
  243. * htmlParser(htmlString, {
  244. * start: function(tag, attrs, unary) {},
  245. * end: function(tag) {},
  246. * chars: function(text) {},
  247. * comment: function(text) {}
  248. * });
  249. *
  250. * @param {string} html string
  251. * @param {object} handler
  252. */
  253. function htmlParser(html, handler) {
  254. if (typeof html !== 'string') {
  255. if (html === null || typeof html === 'undefined') {
  256. html = '';
  257. } else {
  258. html = '' + html;
  259. }
  260. }
  261. var index, chars, match, stack = [], last = html, text;
  262. stack.last = function() { return stack[stack.length - 1]; };
  263. while (html) {
  264. text = '';
  265. chars = true;
  266. // Make sure we're not in a script or style element
  267. if (!stack.last() || !specialElements[stack.last()]) {
  268. // Comment
  269. if (html.indexOf("<!--") === 0) {
  270. // comments containing -- are not allowed unless they terminate the comment
  271. index = html.indexOf("--", 4);
  272. if (index >= 0 && html.lastIndexOf("-->", index) === index) {
  273. if (handler.comment) handler.comment(html.substring(4, index));
  274. html = html.substring(index + 3);
  275. chars = false;
  276. }
  277. // DOCTYPE
  278. } else if (DOCTYPE_REGEXP.test(html)) {
  279. match = html.match(DOCTYPE_REGEXP);
  280. if (match) {
  281. html = html.replace(match[0], '');
  282. chars = false;
  283. }
  284. // end tag
  285. } else if (BEGING_END_TAGE_REGEXP.test(html)) {
  286. match = html.match(END_TAG_REGEXP);
  287. if (match) {
  288. html = html.substring(match[0].length);
  289. match[0].replace(END_TAG_REGEXP, parseEndTag);
  290. chars = false;
  291. }
  292. // start tag
  293. } else if (BEGIN_TAG_REGEXP.test(html)) {
  294. match = html.match(START_TAG_REGEXP);
  295. if (match) {
  296. // We only have a valid start-tag if there is a '>'.
  297. if (match[4]) {
  298. html = html.substring(match[0].length);
  299. match[0].replace(START_TAG_REGEXP, parseStartTag);
  300. }
  301. chars = false;
  302. } else {
  303. // no ending tag found --- this piece should be encoded as an entity.
  304. text += '<';
  305. html = html.substring(1);
  306. }
  307. }
  308. if (chars) {
  309. index = html.indexOf("<");
  310. text += index < 0 ? html : html.substring(0, index);
  311. html = index < 0 ? "" : html.substring(index);
  312. if (handler.chars) handler.chars(decodeEntities(text));
  313. }
  314. } else {
  315. // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\W\w].
  316. html = html.replace(new RegExp("([\\W\\w]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
  317. function(all, text) {
  318. text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
  319. if (handler.chars) handler.chars(decodeEntities(text));
  320. return "";
  321. });
  322. parseEndTag("", stack.last());
  323. }
  324. if (html == last) {
  325. throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
  326. "of html: {0}", html);
  327. }
  328. last = html;
  329. }
  330. // Clean up any remaining tags
  331. parseEndTag();
  332. function parseStartTag(tag, tagName, rest, unary) {
  333. tagName = angular.lowercase(tagName);
  334. if (blockElements[tagName]) {
  335. while (stack.last() && inlineElements[stack.last()]) {
  336. parseEndTag("", stack.last());
  337. }
  338. }
  339. if (optionalEndTagElements[tagName] && stack.last() == tagName) {
  340. parseEndTag("", tagName);
  341. }
  342. unary = voidElements[tagName] || !!unary;
  343. if (!unary)
  344. stack.push(tagName);
  345. var attrs = {};
  346. rest.replace(ATTR_REGEXP,
  347. function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
  348. var value = doubleQuotedValue
  349. || singleQuotedValue
  350. || unquotedValue
  351. || '';
  352. attrs[name] = decodeEntities(value);
  353. });
  354. if (handler.start) handler.start(tagName, attrs, unary);
  355. }
  356. function parseEndTag(tag, tagName) {
  357. var pos = 0, i;
  358. tagName = angular.lowercase(tagName);
  359. if (tagName)
  360. // Find the closest opened tag of the same type
  361. for (pos = stack.length - 1; pos >= 0; pos--)
  362. if (stack[pos] == tagName)
  363. break;
  364. if (pos >= 0) {
  365. // Close all the open elements, up the stack
  366. for (i = stack.length - 1; i >= pos; i--)
  367. if (handler.end) handler.end(stack[i]);
  368. // Remove the open elements from the stack
  369. stack.length = pos;
  370. }
  371. }
  372. }
  373. var hiddenPre=document.createElement("pre");
  374. /**
  375. * decodes all entities into regular string
  376. * @param value
  377. * @returns {string} A string with decoded entities.
  378. */
  379. function decodeEntities(value) {
  380. if (!value) { return ''; }
  381. hiddenPre.innerHTML = value.replace(/</g,"&lt;");
  382. // innerText depends on styling as it doesn't display hidden elements.
  383. // Therefore, it's better to use textContent not to cause unnecessary reflows.
  384. return hiddenPre.textContent;
  385. }
  386. /**
  387. * Escapes all potentially dangerous characters, so that the
  388. * resulting string can be safely inserted into attribute or
  389. * element text.
  390. * @param value
  391. * @returns {string} escaped text
  392. */
  393. function encodeEntities(value) {
  394. return value.
  395. replace(/&/g, '&amp;').
  396. replace(SURROGATE_PAIR_REGEXP, function(value) {
  397. var hi = value.charCodeAt(0);
  398. var low = value.charCodeAt(1);
  399. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  400. }).
  401. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  402. return '&#' + value.charCodeAt(0) + ';';
  403. }).
  404. replace(/</g, '&lt;').
  405. replace(/>/g, '&gt;');
  406. }
  407. /**
  408. * create an HTML/XML writer which writes to buffer
  409. * @param {Array} buf use buf.jain('') to get out sanitized html string
  410. * @returns {object} in the form of {
  411. * start: function(tag, attrs, unary) {},
  412. * end: function(tag) {},
  413. * chars: function(text) {},
  414. * comment: function(text) {}
  415. * }
  416. */
  417. function htmlSanitizeWriter(buf, uriValidator) {
  418. var ignore = false;
  419. var out = angular.bind(buf, buf.push);
  420. return {
  421. start: function(tag, attrs, unary) {
  422. tag = angular.lowercase(tag);
  423. if (!ignore && specialElements[tag]) {
  424. ignore = tag;
  425. }
  426. if (!ignore && validElements[tag] === true) {
  427. out('<');
  428. out(tag);
  429. angular.forEach(attrs, function(value, key) {
  430. var lkey=angular.lowercase(key);
  431. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  432. if (validAttrs[lkey] === true &&
  433. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  434. out(' ');
  435. out(key);
  436. out('="');
  437. out(encodeEntities(value));
  438. out('"');
  439. }
  440. });
  441. out(unary ? '/>' : '>');
  442. }
  443. },
  444. end: function(tag) {
  445. tag = angular.lowercase(tag);
  446. if (!ignore && validElements[tag] === true) {
  447. out('</');
  448. out(tag);
  449. out('>');
  450. }
  451. if (tag == ignore) {
  452. ignore = false;
  453. }
  454. },
  455. chars: function(chars) {
  456. if (!ignore) {
  457. out(encodeEntities(chars));
  458. }
  459. }
  460. };
  461. }
  462. // define ngSanitize module and register $sanitize service
  463. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  464. /* global sanitizeText: false */
  465. /**
  466. * @ngdoc filter
  467. * @name linky
  468. * @kind function
  469. *
  470. * @description
  471. * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
  472. * plain email address links.
  473. *
  474. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  475. *
  476. * @param {string} text Input text.
  477. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
  478. * @returns {string} Html-linkified text.
  479. *
  480. * @usage
  481. <span ng-bind-html="linky_expression | linky"></span>
  482. *
  483. * @example
  484. <example module="linkyExample" deps="angular-sanitize.js">
  485. <file name="index.html">
  486. <script>
  487. angular.module('linkyExample', ['ngSanitize'])
  488. .controller('ExampleController', ['$scope', function($scope) {
  489. $scope.snippet =
  490. 'Pretty text with some links:\n'+
  491. 'http://angularjs.org/,\n'+
  492. 'mailto:us@somewhere.org,\n'+
  493. 'another@somewhere.org,\n'+
  494. 'and one more: ftp://127.0.0.1/.';
  495. $scope.snippetWithTarget = 'http://angularjs.org/';
  496. }]);
  497. </script>
  498. <div ng-controller="ExampleController">
  499. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  500. <table>
  501. <tr>
  502. <td>Filter</td>
  503. <td>Source</td>
  504. <td>Rendered</td>
  505. </tr>
  506. <tr id="linky-filter">
  507. <td>linky filter</td>
  508. <td>
  509. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  510. </td>
  511. <td>
  512. <div ng-bind-html="snippet | linky"></div>
  513. </td>
  514. </tr>
  515. <tr id="linky-target">
  516. <td>linky target</td>
  517. <td>
  518. <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  519. </td>
  520. <td>
  521. <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div>
  522. </td>
  523. </tr>
  524. <tr id="escaped-html">
  525. <td>no filter</td>
  526. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  527. <td><div ng-bind="snippet"></div></td>
  528. </tr>
  529. </table>
  530. </file>
  531. <file name="protractor.js" type="protractor">
  532. it('should linkify the snippet with urls', function() {
  533. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  534. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  535. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  536. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  537. });
  538. it('should not linkify snippet without the linky filter', function() {
  539. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  540. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  541. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  542. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  543. });
  544. it('should update', function() {
  545. element(by.model('snippet')).clear();
  546. element(by.model('snippet')).sendKeys('new http://link.');
  547. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  548. toBe('new http://link.');
  549. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  550. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  551. .toBe('new http://link.');
  552. });
  553. it('should work with the target property', function() {
  554. expect(element(by.id('linky-target')).
  555. element(by.binding("snippetWithTarget | linky:'_blank'")).getText()).
  556. toBe('http://angularjs.org/');
  557. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  558. });
  559. </file>
  560. </example>
  561. */
  562. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  563. var LINKY_URL_REGEXP =
  564. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/,
  565. MAILTO_REGEXP = /^mailto:/;
  566. return function(text, target) {
  567. if (!text) return text;
  568. var match;
  569. var raw = text;
  570. var html = [];
  571. var url;
  572. var i;
  573. while ((match = raw.match(LINKY_URL_REGEXP))) {
  574. // We can not end in these as they are sometimes found at the end of the sentence
  575. url = match[0];
  576. // if we did not match ftp/http/www/mailto then assume mailto
  577. if (!match[2] && !match[4]) {
  578. url = (match[3] ? 'http://' : 'mailto:') + url;
  579. }
  580. i = match.index;
  581. addText(raw.substr(0, i));
  582. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  583. raw = raw.substring(i + match[0].length);
  584. }
  585. addText(raw);
  586. return $sanitize(html.join(''));
  587. function addText(text) {
  588. if (!text) {
  589. return;
  590. }
  591. html.push(sanitizeText(text));
  592. }
  593. function addLink(url, text) {
  594. html.push('<a ');
  595. if (angular.isDefined(target)) {
  596. html.push('target="',
  597. target,
  598. '" ');
  599. }
  600. html.push('href="',
  601. url.replace(/"/g, '&quot;'),
  602. '">');
  603. addText(text);
  604. html.push('</a>');
  605. }
  606. };
  607. }]);
  608. })(window, window.angular);