Debian Codegraph @

demos/hooks-target-blank-demo.html

raw
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <title>DOMPurify demo: Hook to open all links in a new window</title>
6 <script src="../dist/purify.js"></script>
7 </head>
8 <body>
9 <!-- Our DIV to receive content -->
10 <div id="sanitized"></div>
11
12 <!-- Now let's sanitize that content -->
13 <script>
14 'use strict';
15
16 // Specify dirty HTML
17 const dirty = `
18 <a href="?a">CLICK</a>
19 <a href="?a" target="jajaja">CLICK</a>
20 <svg><a href="?svg"><circle r=40></a></svg>
21 <form action="?form"><input type="submit"></form>
22 <img src="404" width="200" height="200" usemap="#test">
23 <map name="test"><area href="?area" shape="rect" coords="0,0,200,200"></area></map>
24 <math href="?mathml">CLICKME</math>
25 <math><mi href="?mathml">CLICKME</mi></math>
26 <math><mi target="xxx" href="?mathml">CLICKME</mi></math>
27 <svg xmlns:xlink="http://www.w3.org/2000/svg"><a xlink:href="?bla"><circle r=40></a></svg>
28 `;
29
30 // Add a hook to make all links open a new window
31 DOMPurify.addHook('afterSanitizeAttributes', (node) => {
32 if ('target' in node) {
33 node.setAttribute('target', '_blank');
34 node.setAttribute('rel', 'noopener noreferrer');
35 }
36 if (!node.hasAttribute('target') && (node.hasAttribute('xlink:href') || node.hasAttribute('href'))) {
37 node.setAttribute('xlink:show', 'new');
38 }
39 });
40
41 // Clean HTML string and write into our DIV
42 const clean = DOMPurify.sanitize(dirty);
43 document.getElementById('sanitized').innerHTML = clean;
44 </script>
45 </body>
46 </html>