Skip to content

Commit 4b6e44a

Browse files
committed
fix: reload main ad script when navigate #18
1 parent c7d669c commit 4b6e44a

2 files changed

Lines changed: 30 additions & 22 deletions

File tree

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/GoogleAdSense.tsx

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1+
"use client";
2+
13
// ref: https://github.com/btk/nextjs-google-adsense/blob/master/src/components/GoogleAdSense.tsx
24
// ref: https://medium.com/frontendweb/how-to-add-google-adsense-in-your-nextjs-89e439f74de3
35

46
import { usePathname } from "next/navigation";
57
import type { ScriptProps } from "next/script";
68
import Script from "next/script";
79
// biome-ignore lint/correctness/noUnusedImports: React refers to a UMD global, but the current file is a module.
8-
import React from "react";
10+
import React, { useEffect } from "react";
911
import { isPublisherId } from "./utils";
1012

1113
interface GoogleAdSenseProps extends Omit<ScriptProps, "src" | "id"> {
@@ -26,24 +28,30 @@ export const GoogleAdSense = ({
2628
const _publisherId =
2729
process.env.NEXT_PUBLIC_ADSENSE_PUBLISHER_ID ?? publisherId;
2830

29-
if (!isPublisherId(_publisherId)) {
30-
console.error(
31-
"❌ [next-google-adsense] Invalid publisherId. It should be like this: pub-xxxxxxxxxxxxxxxx, there is a total of 16 digits behind pub-",
31+
useEffect(() => {
32+
if (!isPublisherId(_publisherId)) {
33+
console.error(
34+
"❌ [next-google-adsense] Invalid publisherId. It should be like this: pub-xxxxxxxxxxxxxxxx, there is a total of 16 digits behind pub-",
35+
);
36+
return;
37+
}
38+
39+
// Remove any previous instance
40+
const existing = document.querySelector(
41+
'script[src*="pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"]',
3242
);
33-
return null;
34-
}
35-
36-
return (
37-
<Script
38-
// Rerender the script when pathname changes to ensure load when navigating pages
39-
key={`adsbygoogle-js-${_publisherId}-${pathname}`}
40-
async={true}
41-
src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-${_publisherId}${
42-
debug ? "google_console=1" : ""
43-
}`}
44-
strategy="afterInteractive"
45-
crossOrigin="anonymous"
46-
{...props}
47-
/>
48-
);
43+
if (existing) {
44+
existing.remove();
45+
}
46+
47+
// Re-insert the script
48+
const script = document.createElement("script");
49+
script.src =
50+
"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXX";
51+
script.async = true;
52+
script.crossOrigin = "anonymous";
53+
document.head.appendChild(script);
54+
}, [pathname, _publisherId]);
55+
56+
return null;
4957
};

0 commit comments

Comments
 (0)