问题可见here
我使用 Sanity 建立了一个网站前端 headless CMS 和 GatsbyJS。
我正在动态查询 URL,以便它可以在 src
中呈现</iframe>
的属性问题是当用户添加包含 &
的 URL 时,对于 Google 日历的嵌入代码来说非常常见。
与 &
该链接不再有效,日历中断(变为空白)。 除非我直接在 src
中对其进行硬编码这正是我们想要避免的。
我怎样才能缓解/避免这个问题并拥有它,以便我可以相应地呈现 URL?
我调查了 encodeURI
, encodeURIComponent
,甚至尝试了这个自定义函数:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
没有骰子...
- 寻找客户端 JS 解决方案或后端解决方案,如果可能的话,在 Sanity 的生态系统中
我目前的实现
// sanity schema
export default {
type: 'document',
title: 'Google Calendar',
name: 'calendar',
fields: [
{
type: 'string',
name: 'Title',
},
{
type: 'url',
name: 'URL',
validation: (Rule) => Rule.required(),
},
],
};
//gastby
export default function GoogleCalendar() {
const { calendar } = useStaticQuery(graphql`
query {
calendar: allSanityCalendar {
nodes {
URL
Title
}
}
}
`);
if (!calendar.nodes.length) return null;
return (
<>
<div>
{calendar.nodes.map((node) => (
<iframe
src={node.URL}
id="test"
title={node.Title}
width="100%"
height="1000px"
async
/>
))}
</div>
</>
);
}
这是一个说明问题的沙箱: https://stackblitz.com/edit/iframe-dynamic-src
最佳答案
在这里,您的沙箱正在运行:https://iframe-dynamic-src-pmxqbb.stackblitz.io
我已经通过以下方式修复了它:
<iframe
src={decodeURIComponent(
encodeURIComponent(brokeUrl.replace(/&/g, "&"))
)}
width="800"
height="600"
frameborder="0"
scrolling="no"
content
/>
关于javascript - 转义 HTML 实体并动态呈现 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65434185/