How To Test Adsense Ads On Locally (Kinda) — Easy Solution (2024)

Shivam Bhalla
2 min readApr 30, 2024

--

I don’t belive it’s fully possible to test adsense ads locally easily (please comment if there is a super easy solution). In the meantime, the approach I took is the following:

import Router from "next/router";
import { useEffect } from "react";
declare global {
interface Window {
adsbygoogle: unknown[];
}
}

interface AdsBannerProps {
"data-ad-slot": string;
"data-ad-format": string;
"data-full-width-responsive": string;
"data-ad-layout"?: string;
}

const AdBanner = (props: AdsBannerProps) => {
useEffect(() => {
const handleRouteChange = () => {
const intervalId = setInterval(() => {
try {
// Check if the 'ins' element already has an ad in it
if (window.adsbygoogle) {
window.adsbygoogle.push({});
clearInterval(intervalId);
}
} catch (err) {
console.error("Error pushing ads: ", err);
clearInterval(intervalId); // Ensure we clear interval on errors too
}
}, 100);
return () => clearInterval(intervalId); // Clear interval on component unmount
};

// Run the function when the component mounts
handleRouteChange();

// Subscribe to route changes
if (typeof window !== "undefined") {
Router.events.on("routeChangeComplete", handleRouteChange);

// Unsubscribe from route changes when the component unmounts
return () => {
Router.events.off("routeChangeComplete", handleRouteChange);
};
}
}, []);

return (
<ins
className="adsbygoogle adbanner-customize mt-2"
style={{
display: "block",
overflow: "hidden",
border: process.env.NODE_ENV === "development" ? "1px solid red" : "none",
background: process.env.NODE_ENV === "development" ? "rgba(255, 0, 0, 0.1)" : "none",
}}
data-adtest="on"
data-ad-client={process.env.NEXT_PUBLIC_GOOGLE_ADS_CLIENT_ID}
{...props}
/>
);
};
export default AdBanner;

The key code here is:

style={{
display: "block",
overflow: "hidden",
border: process.env.NODE_ENV === "development" ? "1px solid red" : "none",
background: process.env.NODE_ENV === "development" ? "rgba(255, 0, 0, 0.1)" : "none",
}}

That’s about it. If you find it helpful, consider upvoting this article and checking out frontendlead.com, an all in one platform to help you prepare for frontend interviews.

Cheers.

Shivam

--

--