我想用mailto发送一封电子邮件:这封邮件包含几个单词和一个js脚本。此脚本不需要执行。这只是为了让接收者复制和粘贴。
脚本:
<script id="myID">var script = document.createElement("script");script.src="script-to-inject.js?id=myID&type=0&name=Name&size=120";document.head.appendChild(script); </script>
And my mailto:
window.location.href = "mailto:"+email+"?subject="+subject+"&body=FewWords"+ script;
当我的邮件打开时,我有这样的内容:
<script id="myID">var script = document.createElement("script");script.src="script-to-inject.js?id=myID
脚本的结尾没有出现(在第一个&
之后)
我怎么能解决这个问题?谢谢!
您忘记对URL参数进行编码,因此&
开始下一个参数
您可以使用encodeURIComponent
函数:
window.location.href = "mailto:" + encodeURIComponent(email) +
"?subject=" + encodeURIComponent(subject) +
"&body=" + encodeURIComponent("FewWords" + script);
另一种更简洁的方法是使用URLSearchParams
:
const url = new URL(`mailto:${encodeURIComponent(email)}`)
url.searchParams.set('subject', subject)
url.searchParams.set('body', 'FewWords' + script)
window.location.href = url
设置href属性时,需要正确转义电子邮件、主题和脚本。如果这些变量包含&
或=
字符怎么办?你可以看到这会被误解。
试试这个:
window.location.href = "mailto:"
+ encodeURIComponent(email)
+ "?subject="
+ encodeURIComponent(subject)
+ "&body=FewWords"
+ encodeURIComponent(script);
(我不确定您是否可以在body
参数中传递HTML,顺便说一下,它可能会被解释为纯文本。)
您也可以使用URLSearchParams
:
const params = new URLSearchParams();
params.append('subject', subject);
params.append('body', 'FewWords' + script);
window.location.href = 'mailto:' + encodeURIComponent(email) + '?' + params.toString();