3

问题可以在这里看到

我在前端使用Sanity无头 CMS 和 GatsbyJS构建了一个站点。

我正在动态查询 URL,以便它可以在src属性内呈现</iframe>问题是当用户添加一个包含 的 URL 时&amp,这对于 Google 日历的嵌入代码非常常见。

随着&amp链接不再有效并且日历中断(变为空白)。除非我直接在src其中硬编码它,这正是我们想要避免的。

我怎样才能减轻/逃避这个问题并拥有它,以便我可以相应地呈现 URL?

我研究过encodeURI, encodeURIComponent,甚至尝试过这个自定义函数:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

没有骰子...

  • 如果可能的话,在 Sanity 的生态系统中寻找客户端 JS 解决方案或后端解决方案

我目前的实现

// 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

4

1 回答 1

1

你的沙箱在这里工作:https ://iframe-dynamic-src-pmxqbb.stackblitz.io

我已经通过以下方式修复了它:

  <iframe
    src={decodeURIComponent(
      encodeURIComponent(brokeUrl.replace(/&amp;/g, "&"))
    )}
    width="800"
    height="600"
    frameborder="0"
    scrolling="no"
    content
  />

解码一个编码的URL,&amp;&.

于 2020-12-24T15:21:43.370 回答