我正在为盲人(好吧,无论如何都是合法的盲人)制作一个电子邮件客户端,并且我正在尝试以安全的方式呈现电子邮件的 HTML 正文,但不会丢失原始内容的风格。我还希望所有内容都增加尺寸,尤其是文本。
最佳答案
我建议使用iframe
,它可以通过sandbox
属性阻止脚本执行。您可以添加其他样式来设置特定的根字体大小,尽管这可能无法按预期工作,具体取决于邮件本身的样式。
<script>
let mail = `
<h1>Title</h1>
Lorem ipsum dolor sit
<!-- Svelte parser does not like additional script tags. -->
<${''}script>alert('!')</${''}script>
`;
$: document = mail + `
<style>
html, body { font-size: 32px; }
</style>
`
</script>
<iframe srcdoc={document} title="Mail message" sandbox />
<style>
iframe {
border: none;
width: 100%;
height: 100%;
}
</style>
作为字体大小的替代方案,可以使用变换来放大整个框架,其大小必须按比例缩小:
iframe {
border: none;
width: calc(100% / 2);
height: calc(100% / 2);
transform-origin: 0 0;
transform: scale(2);
}
如果您需要更直接地访问生成的内容,例如通过事件,您可以使用各种库之一(例如 xss
或 sanitize-html
)来清理 HTML。然后可以使用 {@html ...}
插入 HTML。
要处理链接上的点击,您可以将内容包装在元素中并在那里处理点击,检查目标
是否是链接元素。
<script>
let mail = `
<h1>Title</h1>
<a href="http://stackoverflow.com">Stack Overflow</a>
`;
function sanitize(html) {
// Use some sanitizer package here
return html;
}
function onClick(e) {
if (e.target.tagName == 'A') {
e.preventDefault();
alert('Links to: ' + e.target.href);
}
}
</script>
<div class="container" on:click={onClick}>
{@html sanitize(mail)}
</div>
<style>
.container {
border: none;
width: calc(100% / 2);
height: calc(100% / 2);
transform-origin: 0 0;
transform: scale(2);
}
</style>
(省略清理,因为提到的包与 REPL 不兼容。)
关于html-email - 清理电子邮件 html 正文并增加 HTML 缩放级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72931543/