gpt4 book ai didi

reactjs - 在 Next JS 中获取 AdSense 广告以在路由更改时重新加载

转载 作者:行者123 更新时间:2023-12-05 05:43:31 42 4
gpt4 key购买 nike

我们已经在我们的 Next.JS 网站上实现了 Google AdSense,但我们希望在路线发生变化时重新加载广告。

这是我尝试过的:

const AdBlock = props => {
const { userLoaded, currentUserIsSilverPlus } = useAuth()

useEffect(() => {
window.adsbygoogle = window.adsbygoogle || []
window.adsbygoogle.push({})
}, [])

const reloadAds = () => {
const { googletag } = window
if (googletag) {
googletag.cmd.push(function () {
googletag.pubads().refresh()
})
}
}

Router.events.on("routeChangeStart", reloadAds)

if (userLoaded && !currentUserIsSilverPlus) {
return (
<ins
className="adsbygoogle adbanner-customize"
style={{ display: "block" }}
data-ad-client="ca-pub-1702181491157560"
data-ad-slot={props.slot}
data-ad-format={props.format}
data-full-width-responsive={props.responsive}
/>
)
}
return ""
}

export default AdBlock

广告加载,但是,它们似乎永远不会刷新。我错过了什么?

最佳答案

我的解决方案是观察路由器事件变化,当 routeChangeStart 广告必须卸载时,当 routeChangeComplete 广告必须重新安装时。

// components/Adsense.tsx

function Ads() {
const adsRef = useRef<HTMLModElement | null>(null);

useEffect(() => {
const executeWindowAds = () => {
try {
// @ts-ignore
(adsbygoogle = window.adsbygoogle || []).push({});
} catch (error: any) {
console.error('error ads======>', error.message);
}
};

const insHasChildren = adsRef.current?.childNodes.length;
if (!insHasChildren) {
executeWindowAds();
}
}, []);

return (
<ins
ref={adsRef}
className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client="ca-pub-xxx"
data-ad-slot="xxx"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
);
}

export default function Adsense() {
const router = useRouter();
const [shouldMount, setShouldMount] = useState(true);

useEffect(() => {
const onRouteChangeStart = () => setShouldMount(false);
const onRouteChangeComplete = () => setShouldMount(true);

router.events.on('routeChangeStart', onRouteChangeStart);
router.events.on('routeChangeComplete', onRouteChangeComplete);

return () => {
router.events.off('routeChangeStart', onRouteChangeStart);
router.events.off('routeChangeComplete', onRouteChangeComplete);
};
}, [router.events]);

return shouldMount ? <Ads /> : null;
}

在您的布局页面上,例如每个页面都有相同侧边栏的侧边栏:

// components/LayoutBlogPost.tsx

import dynamic from 'next/dynamic';
const Adsense = dynamic(() => import('./Adsense'), { ssr: false });

export default function LayoutBlogPost({children}: {children: any}) {
return (
<div>
{children}
<Adsense />
</div>
);
}

关于reactjs - 在 Next JS 中获取 AdSense 广告以在路由更改时重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71806453/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com