[Next Js] Adsense code in react markdown

JuneTein

May 9, 2023

Adsense code into React Markdown

Google Adsense code is consist of div, ins and script HTML tags. If you add these into markdown file then it would not work properly.

As same as my former post about inserting iframe tag. I imported rehype-plugins.

See my post for iframe tag

First you need to install plugins

    npm install rehype-raw
    // and
    npm install rehype-sanitize

and the Second import plugins on the top.

    import rehypeRaw from "rehype-raw";
    import rehypeSanitize, { defaultSchema } from "rehype-sanitize";

Adjusting rehype-sanitize

rehypeRaw is for put HTML tags inside of your .md file. and rehype-sanitize is for sanitize your HTML.

Your code may like this.

    <ReactMarkdown components={customRenderers}>{content}</ReactMarkdown>

Third we need to add rehype-raw and rehype-sanitize

<ReactMarkdown
              rehypePlugins={[
                rehypeRaw,
                rehypeSanitize({
                  ...defaultSchema,
                  attributes: {
                    ...defaultSchema.attributes,
                    iframe: [...(defaultSchema.attributes.iframe || [])],
                    ins: [
                      ...(defaultSchema.attributes.ins || [
                        "class",
                        "style",
                        "data-ad-client",
                        "data-ad-slot",
                      ]),
                    ],
                    script: [
                      ...(defaultSchema.attributes.script || ["async", "src"]),
                    ],
                    "*": ["class"],
                    div: [...(defaultSchema.attributes.div || [])],
                  },
                }),
              ]}
              components={customRenderers}
            >
              {content}
            </ReactMarkdown>

RehypeSanitize will ignore all of your HTML tags. So you need to add exceptions. This is what attributes are doing.

At last you can add google adsense code inside of your markdown documents like below.

    <div className="ad">
      <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
      <ins className="adsbygoogle"
        style={{ display: "inline-block", width: 320, height: 50 }}
        data-ad-client="ca-pub-1234567890"
        data-ad-slot="1234567890"></ins>
      <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
      </script>
    </div>

If your website did import the script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" line in the _app.js or _document.js then you don't need to write it in the .md file again. Then it works like below.

ads would not be shown time to time. If you refresh this page ads may be shown. it's google's choice. You can see div for ads in the developer's tool

Faced Error with permission Policy....?

Click here for solution


이것도 역시 구글에서 아무리 뒤져도 안나오길래 영어로 검색하는 분들이 있을걸로 생각해서 영어로 설명했습니다.

간단히 요약하면 iframe 태크 넣는 것과 마찬가지로 rehypeRaw를 써야 HTML tag를 쓸 수 있습니다. rehype-sanitize는 HTML 태그를 삭제하는 역할을 합니다. 이전 포스팅 참고하세요.

attributes내에 sanitize되면 안되는 div, ins, script태그를 예외로 설정 해주고 클래스명도 날려버리면 안되니 *표로 예외지정 해줍니다. 그리고 문서 중간에 adsense에서 복사해 온 코드를 넣어주면 됩니다.

한가지 발생하는 오류는 퍼미션 팔러시 오류가 나올 수 있습니다. 이것은 여기를 클릭하셔서 해결하시기 바랍니다.

kakao_share_button

카카오톡 공유하기 →