The problem can be seen here
I built a site using Sanity headless CMS and GatsbyJS on the frontend.
I'm querying URLs dynamically so that it can be rendered inside the src attribute of an </iframe> The problem is when the user adds an URL containing &, pretty common for Google Calendar's embed code.
With & The link no longer works and the calendar breaks (goes blank). Unless I hardcode it directly in the src which is exactly what we want to avoid.
How can I mitigate/escape this issue and have it so I can render the URL accordingly?
I've looked into encodeURI , encodeURIComponent, even tried this custom function:
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
No dice...
My current implementation
// 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>
</>
);
}
Here's a sandbox illustrating the issue: https://stackblitz.com/edit/iframe-dynamic-src
Here you have your sandbox working: https://iframe-dynamic-src-pmxqbb.stackblitz.io
I've fixed it by:
<iframe
src={decodeURIComponent(
encodeURIComponent(brokeUrl.replace(/&/g, "&"))
)}
width="800"
height="600"
frameborder="0"
scrolling="no"
content
/>
Decoding an encoded URL that replaces globally the ampersands (&) by &.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With