Skip to content

Reinitiate/reload ads on page change #48

Description

@maxeth

Hey,

I was wondering how you're handling page changes so that the ads get reinitiated/readjusted to the layout changes.

For example, on the adsense dashboard, I excluded the index and contact page to NOT contain any ads. When I visit example.com/ this works just as expected, but when I visit some other blog post first, and then use next.js's client-side router to change the route to the index page example.com/, the ads just remain in the "blog layout" as if the window location never actually changed. This breaks the whole page layout of the newly navigated-to page.

I saw something like this to "reload" ads on page changes online, but it seems to do absolutely nothing in my case:

  const router = useRouter();


  useEffect(() => {
    if ((window as any).adsbygoogle) {
      const adsC = document.getElementsByClassName("adsbygoogle").length;
      for (let i = 0; i < adsC; i++) {
        try {
          ((window as any).adsbygoogle =
            (window as any).adsbygoogle || []).push({});
        } catch (e) {}
      }
    }
    return () => {
      if ((window as any).adsbygoogle) {
        const adsC = document.getElementsByClassName("adsbygoogle").length;
        for (let i = 0; i < adsC; i++) {
          try {
            ((window as any).adsbygoogle =
              (window as any).adsbygoogle || []).push({});
          } catch (e) {}
        }
      }
    };
  }, [router, router.pathname]);

I see you do something similar for ResponsiveAdUnit.tsx, but what about the auto ads spread all around the pages?

Thanks 🙂

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions