Skip to main content

Google AdSense 表示 (全ページ共通)

Google AdSense 管理画面

  1. AdSense 管理画面で広告ユニットを作成
  2. 「広告」→「広告ユニットごと」→「ディスプレイ広告」などを選択
  3. 「レスポンシブ」に設定

Docusaurus 側対応の概要

  1. docusaurus.config.ts に scripts で AdSense の JS を追加
    • 全てのページの head で呼ばれる
  2. window.adsbygoogle の型定義を足す
    • これは VSCode で出る警告避け
  3. AdSense 表示用にカスタムタグ作成
  4. カスタムタグの呼び出し

1. docusaurus.config.ts の記載箇所

docusaurus.config.ts
const config: Config = {
...
scripts: [
{
src: "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",
async: true,
'data-ad-client': 'ca-pub-XXXXXXXXXXXXXXXXXXXXX',
crossorigin: "anonymous",
},
],

2. 型定義の追加

src/types/global.d.ts
export {};

declare global {
interface Window {
adsbygoogle?: unknown[];
}
}

3. AdSense 表示用にカスタムタグ作成

src/components/AdsenseBlock.tsx
import React, { useEffect } from 'react';

type Props = {
style?: React.CSSProperties;
format?: 'auto' | 'horizontal' | 'vertical' | 'rectangle';
className?: string;
};

const AD_CLIENT = 'ca-pub-xxxxxxxxxxxxxxxx';
const AD_SLOT = 'XXXXXXXXX';

const AdsenseBlock: React.FC<Props> = (props) => {
const { style, format, className } = props;

useEffect(() => {
if (typeof window === 'undefined') {
return;
}

if (!window.adsbygoogle) {
window.adsbygoogle = [];
}

try {
window.adsbygoogle.push({});
} catch (error) {
// eslint-disable-next-line no-console
console.warn('AdSense push failed:', error);
}
}, []);

return (
<ins
className={`adsbygoogle ${className ?? ''}`}
style={style ?? { display: 'block' }}
data-ad-client={AD_CLIENT}
data-ad-slot={AD_SLOT}
data-ad-format={format ?? 'auto'}
data-full-width-responsive="true"
/>
);
};

export default AdsenseBlock;

4. カスタムタグの呼び出し

4-1. 個別に埋め込むだけで良い場合

mdx
import AdsenseBlock from '@site/src/components/AdsenseBlock';

# 記事タイトル

本文...

<AdsenseBlock />

本文の続き...

ためしにここに表示

広告サンプル

4-2. Doc ページのフッタに共通で入れる場合

4-2-1. フッタ用に Swizzle する

bash
npx docusaurus swizzle @docusaurus/theme-classic DocItem/Footer --eject --typescript

src/theme/DocItem/Footer/index.tsx が作成される

4-2-2. DocItem/Footer/index.tsx に足す

src/theme/DocItem/Footer/index.tsx
import AdsenseBlock from '@site/src/components/AdsenseBlock';

// ...
<footer> ... 既存 ... </footer>

<div style={{ marginTop: '2rem', textAlign: 'center' }}>
<AdsenseBlock />
</div>

このページでも、下の方に出てるはず。


以下広告