Skip to content

Commit

Permalink
fix(js): Escape HTML in templates
Browse files Browse the repository at this point in the history
  • Loading branch information
mieko committed Sep 27, 2020
1 parent 656aa11 commit 8815b91
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 10 deletions.
6 changes: 4 additions & 2 deletions src/js/templates/dropdown-item.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { escape } from "../utils/dom";

export default (data) => {
return `<a href="javascript:void(0);" class="dropdown-item" data-value="${data.value}" data-text="${data.text}">${data.text}</a>`;
};
return `<a href="javascript:void(0);" class="dropdown-item" data-value="${escape(data.value)}" data-text="${escape(data.text)}">${escape(data.text)}</a>`;
};
8 changes: 5 additions & 3 deletions src/js/templates/tag.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { escape } from "../utils/dom";

export default (data) => {
return `<span class="tag ${data.style}" data-value="${data.value}">
${data.text}
return `<span class="tag ${escape(data.style)}" data-value="${escape(data.value)}">
${escape(data.text)}
${data.removable ? '<div class="delete is-small" data-tag="delete"></div>' : ''}
</span>`;
};
};
10 changes: 6 additions & 4 deletions src/js/templates/wrapper.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { escape } from "../utils/dom";

export default (data) => {
return `<div class="tags-input">
<input class="input" type="text" placeholder="${data.placeholder}">
<div id="${data.uuid}-list" class="dropdown-menu" role="menu">
<input class="input" type="text" placeholder="${escape(data.placeholder)}">
<div id="${escape(data.uuid)}-list" class="dropdown-menu" role="menu">
<div class="dropdown-content">
<span class="dropdown-item empty-title">${data.emptyTitle}</span>
<span class="dropdown-item empty-title">${escape(data.emptyTitle)}</span>
</div>
</div>
</div>`;
};
};
18 changes: 17 additions & 1 deletion src/js/utils/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,20 @@ export const cloneAttributes = (target, source, except = null) => {
target.setAttribute(attr.nodeName === "id" ? 'data-id' : attr.nodeName, attr.nodeValue);
}
});
}
};

/**
* Escapes string for insertion into HTML, replacing special characters with HTML
* entities.
* @param {String} string
*/
export const escape = (string) => {
return string.replace(/(['"<>])/g, (char) => {
return {
'<': '&lt;',
'>': '&gt;',
'"': "&quot;",
"'": "&#39;"
}[char];
});
};

0 comments on commit 8815b91

Please sign in to comment.