Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 131 additions & 60 deletions docs/content/scripts/ads/google-adsense.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,91 +12,159 @@ links:
size: xs
---

[Google Adsense](https://www.google.com/adsense/start/) allows you to monetize your website by displaying relevant ads from Google.
[Google AdSense](https://www.google.com/adsense/start/) allows you to monetize your website by displaying relevant ads from Google.

Nuxt Scripts provides a `useScriptGoogleAdsense` composable and a headless `ScriptGoogleAdsense` component to interact with Google Adsense.
Nuxt Scripts provides:

- `useScriptGoogleAdsense`: A composable to manage Google AdSense dynamically.
- `<ScriptGoogleAdsense>`: A headless component to embed ads directly in your Nuxt app.

## Global Setup

You can configure Google Adsense globally in your `nuxt.config.ts` file so the script is automatically loaded on all pages.
You can configure Google AdSense **globally** in your `nuxt.config.ts` so that the script is automatically loaded on all pages.

```ts [nuxt.config.ts]
export default defineNuxtConfig({
scripts: {
registry: {
googleAdsense: {
client: 'ca-pub-<your-id>', // Your Google AdSense Publisher ID
client: "ca-pub-<your-id>", // Your Google AdSense Publisher ID
autoAds: true, // Enable Auto Ads
}
}
}
})
},
},
},
});
```

## Where to Find `<your-id>`
Your **Google AdSense Publisher ID** (also known as `ca-pub-XXXXXXX`) can be found in your **Google AdSense Account**:
## Where to Find `<your-id>` (Publisher ID)

1. Log in to your **Google AdSense** account.
2. Navigate to **Account > Settings** (click on your profile icon > "Account information").
3. Locate the **Publisher ID** under **Account Information**.
4. Replace `<your-id>` in the config above with your actual ID.
Your **Google AdSense Publisher ID** (also known as `ca-pub-XXXXXXX`) can be found in your **Google AdSense Account**:

> **Note**: You can also manage Auto Ads settings directly from [Google Adsense](https://adsense.google.com/start/), where you can control ad types, placements, and optimization for higher revenue.
1. Log in to your **Google AdSense** account.
2. Navigate to **Account > Settings** (click on your profile icon > "Account information").
3. Locate the **Publisher ID** under **Account Information**.
4. Replace `<your-id>` in the config above with your actual ID.

## Site Ownership Verification
::callout{icon="i-heroicons-light-bulb" to="https://adsense.google.com/start/" target="_blank"}
You can also manage **Auto Ads settings** from your **Google AdSense Dashboard** to control *ad types, placements, and revenue optimization*.
::

### Using *meta tag* for Verification
When a `client` is provided, a **meta tag** will be inserted on the page so that Google can verify your site ownership.
## Site Ownership Verification

```ts
const adsense = useScriptGoogleAdsense({
client: 'ca-pub-<your-id>',
})
```
### Automatic Meta Tag Insertion

If a `client` is provided, a **meta tag** will be inserted on the page **automatically** for Google to verify your site ownership.

::tabs
::div
---
label: Example
icon: i-heroicons-code-bracket-square
---
```ts [nuxt.config.ts]
export default defineNuxtConfig({
scripts: {
registry: {
googleAdsense: {
client: "ca-pub-<your-id>", // AdSense Publisher ID
},
},
},
});
```
::
::div
---
label: Output
icon: i-heroicons-magnifying-glass-circle
---
```html
<meta name="google-adsense-account" content="ca-pub-<your-id>" />
```
::
::

The generated meta tag will look like this:
### Using `ads.txt` for Verification

```html
<meta name="google-adsense-account" content="ca-pub-<your-id>">
```
Google recommends adding an `ads.txt` file for **ad revenue eligibility**.

### Using `ads.txt` for Verification
Alternatively, add an `ads.txt` file to your `public/` directory to ensure ad revenue eligibility.
#### Steps:

1. Create a new file: `public/ads.txt`
2. Add the following content:

```plaintext
google.com, pub-<your-id>, DIRECT, f08c47fec0942fa0
```

```plaintext
google.com, pub-<your-id>, DIRECT, f08c47fec0942fa0
```
3. Replace `<your-id>` with your **AdSense Publisher ID**.

> **Why is `ads.txt` important?**
> Adding this file helps prevent **ad fraud** and ensures that only your site can display your ads.

## `ScriptGoogleAdsense` Component

The `ScriptGoogleAdsense` component is a wrapper around the `useScriptGoogleAdsense` composable. It provides a simple way to embed ads in your Nuxt app.
::callout{icon="i-heroicons-light-bulb"}
**Why use `ads.txt`?** It helps **prevent ad fraud** and ensures that **only your site** can display your ads.
::

## Enabling Auto Ads

Auto Ads allow Google to **automatically** place ads for **better optimization**.

::tabs
::div
---
label: Example
icon: i-heroicons-code-bracket-square
---
```ts [nuxt.config.ts]
export default defineNuxtConfig({
scripts: {
registry: {
googleAdsense: {
client: "ca-pub-<your-id>", // AdSense Publisher ID
autoAds: true, // Enable Auto Ads
},
},
},
});
```
::
::div
---
label: Output
icon: i-heroicons-magnifying-glass-circle
---
```html
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-<your-id>",
enable_page_level_ads: true,
});
</script>
```
::
::

## Using `ScriptGoogleAdsense` Component

It provides a simple way to **embed ads** in your Nuxt app.

```vue
<template>
<ScriptGoogleAdsense
data-ad-client="ca-pub-..."
data-ad-slot="..."
data-ad-client="ca-pub-<your-id>"
data-ad-slot="1234567890"
data-ad-format="auto"
/>
</template>
```

### Component Props

- `data-ad-client`: **(Required)** Your **Google Adsense Publisher ID** (`ca-pub-XXXXXXXXXX`).
- `data-ad-slot`: **(Required)** Your **Ad Slot ID** (available in AdSense dashboard).
- `data-ad-format`: Ad format type (`auto`, `rectangle`, `horizontal`, `vertical`, `fluid`, `autorelaxed`).
- `data-ad-layout`: Layout (`in-article`, `in-feed`, `fixed`).
- `data-full-width-responsive`: **Set to `true`** to make the ad responsive.
| Prop | Description |
| ---------------------------- | --------------------------------------------------------------------- |
| `data-ad-client` | Your **Google Adsense Publisher ID**(`ca-pub-XXXXXXXXXX`). |
| `data-ad-slot` | Your **Ad Slot ID** (available in AdSense dashboard). |
| `data-ad-format` | Ad format type (`auto`, `rectangle`, `horizontal`, `vertical`, `fluid`, `autorelaxed`). |
| `data-ad-layout` | Layout (`in-article`, `in-feed`, `fixed`). |
| `data-full-width-responsive` | **Set to `true`** to make the ad responsive. |

### Example Usage with `data-ad-layout`
#### Example Usage with `data-ad-layout`

To specify a layout for your ads (such as "in-article"), you can use the `data-ad-layout` attribute:

Expand All @@ -111,30 +179,29 @@ To specify a layout for your ads (such as "in-article"), you can use the `data-a
</template>
```

### How to Handle Ad-Blockers?
## How to Handle Ad-Blockers?

You can use these hooks to add a fallback when the Google Adsense script is blocked.
If a user has an **ad-blocker enabled**, you can show **fallback content**.

```vue
<template>
<ScriptGoogleAdsense
data-ad-client="ca-pub-..."
data-ad-slot="..."
>
<ScriptGoogleAdsense data-ad-client="ca-pub-..." data-ad-slot="...">
<template #error>
<!-- Fallback content -->
Please support us by disabling your ad blocker.
<p>Please support us by disabling your ad blocker.</p>
</template>
</ScriptGoogleAdsense>
</template>
```

## `useScriptGoogleAdsense` Composable
## Using `useScriptGoogleAdsense` Composable

The `useScriptGoogleAdsense` composable gives fine-grain control over the Adsense script management.
The `useScriptGoogleAdsense` composable allows **fine-grain control** over the AdSense script.

```ts
export function useScriptGoogleAdsense<T extends GoogleAdsenseApi>(_options?: GoogleAdsenseInput) {}
export function useScriptGoogleAdsense<T extends GoogleAdsenseApi>(
_options?: GoogleAdsenseInput
) {}
```

See the [Registry Scripts Guide](/docs/guides/registry-scripts) for advanced usage.
Expand All @@ -145,7 +212,7 @@ This interface defines the structure of the Google Adsense API for better TypeSc

```ts
export interface GoogleAdsenseApi {
adsbygoogle: any[] & { loaded: boolean }
adsbygoogle: any[] & { loaded: boolean };
}
```

Expand All @@ -163,5 +230,9 @@ export const GoogleAdsenseOptions = object({
* Enable or disable Auto Ads.
*/
autoAds: optional(boolean()),
})
});
```

::callout{icon="i-heroicons-light-bulb" to="https://support.google.com/adsense" target="_blank"}
Need more help? Check out the official **Google AdSense Guide**
::
2 changes: 1 addition & 1 deletion playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const thirdParties = [
},
{
name: 'Matomo Analytics',
path: '/third-parties/matomo-analytics',
path: '/third-parties/matomo-analytics/default',
},
{
name: 'Hotjar',
Expand Down
29 changes: 14 additions & 15 deletions src/runtime/registry/google-adsense.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export function useScriptGoogleAdsense<T extends GoogleAdsenseApi>(_options?: Go
// Note: inputs.useScriptInput is not usable, needs to be normalized
return useRegistryScript<T, typeof GoogleAdsenseOptions>('googleAdsense', options => ({
scriptInput: {
src: `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js${options?.client ? `?client=${options.client}` : ''}`,
src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
},
schema: import.meta.dev ? GoogleAdsenseOptions : undefined,
scriptOptions: {
Expand All @@ -46,26 +46,25 @@ export function useScriptGoogleAdsense<T extends GoogleAdsenseApi>(_options?: Go
beforeInit() {
if (options?.client) {
useHead({
// Add meta tag for Google Adsense account
meta: [
{
name: 'google-adsense-account',
content: options?.client,
content: options.client,
},
],
// Inject Auto Ads script dynamically
script: options.autoAds
? [
{
innerHTML: `
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "${options.client}",
enable_page_level_ads: true
});
`,
type: 'text/javascript',
},
]
: [],
script: [
{
innerHTML: `
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "${options.client}",
enable_page_level_ads: ${options.autoAds ?? false}
});
`,
type: 'text/javascript',
},
],
})
}
},
Expand Down