【问题标题】:Escape HTML entities and render URL dynamically转义 HTML 实体并动态呈现 URL
【发布时间】:2021-04-02 15:52:31
【问题描述】:

问题可以看here

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

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

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

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

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

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

【问题讨论】:

    标签: javascript reactjs ecmascript-6 gatsby sanity


    【解决方案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
      />
    

    Decoding 一个 encoded URL,将与符号 (&amp;amp;) 全局替换为 &amp;

    【讨论】:

    • 太棒了!非常感谢 - 在客户端而不是服务器端这样做有什么顾虑吗?
    • 嗯,您可以节省给客户端的任何计算工作都是为了性能,但这始终取决于您的设置、用例(尤其是)/需求和功能
    猜你喜欢
    • 2014-01-27
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多