[英]Escape HTML entities and render URL dynamically
問題可以在這里看到
我在前端使用Sanity無頭 CMS 和 GatsbyJS 構建了一個站點。
我正在動態查詢 URL,以便它可以在</iframe>
的src
屬性中呈現問題是當用戶添加一個包含&
的 URL 時,這對於 Google 日歷的嵌入代碼非常常見。
使用&
鏈接不再有效,日歷中斷(變為空白)。 除非我直接在src
中硬編碼它,這正是我們想要避免的。
我怎樣才能減輕/逃避這個問題並擁有它,以便我可以相應地渲染 URL?
我研究了encodeURI
, encodeURIComponent
,甚至嘗試過這個自定義 function:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
沒有骰子...
我目前的實現
// 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
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.