转义 HTML 个实体并动态呈现 URL
Escape HTML entities and render URL dynamically
问题可见here
我在前端使用 Sanity headless CMS 和 GatsbyJS 构建了一个站点。
我正在动态查询 URL,以便它可以在 </iframe>
的 src
属性内呈现 问题是当用户添加 URL包含 &
,对于 Google 日历的嵌入代码很常见。
&
link 不再有效,日历中断(变为空白)。 除非我直接在src
中硬编码,这正是我们想要避免的。
如何 mitigate/escape 这个问题并得到它,以便我可以相应地呈现 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
/>
全局替换符号 (&
)
问题可见here
我在前端使用 Sanity headless CMS 和 GatsbyJS 构建了一个站点。
我正在动态查询 URL,以便它可以在 </iframe>
的 src
属性内呈现 问题是当用户添加 URL包含 &
,对于 Google 日历的嵌入代码很常见。
&
link 不再有效,日历中断(变为空白)。 除非我直接在src
中硬编码,这正是我们想要避免的。
如何 mitigate/escape 这个问题并得到它,以便我可以相应地呈现 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
/>
全局替换符号 (&
)