簡體   English   中英

轉義 HTML 實體並動態渲染 URL

[英]Escape HTML entities and render URL dynamically

問題可以在這里看到

我在前端使用Sanity無頭 CMS 和 GatsbyJS 構建了一個站點。

我正在動態查詢 URL,以便它可以在</iframe>src屬性中呈現問題是當用戶添加一個包含&amp的 URL 時,這對於 Google 日歷的嵌入代碼非常常見。

使用&amp鏈接不再有效,日歷中斷(變為空白)。 除非我直接在src中硬編碼它,這正是我們想要避免的。

我怎樣才能減輕/逃避這個問題並擁有它,以便我可以相應地渲染 URL?

我研究了encodeURIencodeURIComponent ,甚至嘗試過這個自定義 function:

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

你的沙箱在這里工作: 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; ) 全局替換為&

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM