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