2

Is it possible to add AdSense's ad unit to the body of a Docusaurus web page?

Whenever I paste the Display ad unit code into a markdown page of my site, the browser throws "Uncaught SyntaxError: expected expression, got end of script".

BTW, I am not referring to the sidebar area. I need it within the content of the pages.

Any ideas on how to add it successfully? Thanks.

  • I don't know how you could add it only to some pages. There are site-wide settings as far as I can tell. Take a look at https://stackoverflow.com/questions/57859350/how-can-i-add-custom-scripts-in-index-htmls-head-part-in-docusaurus-v2 and https://github.com/facebook/docusaurus/pull/1831 – KWriter Sep 02 '22 at 05:02

1 Answers1

0

Not conveniently on a single page rendered by the docs plugin, no, but you could insert it as a custom sidebar setup:

module.exports = {
  myHtmlSidebar: [
    {
      type: 'html',
      value: '<div class="my_ad_div"></div>', 
      defaultStyle: true, // Use the default menu item styling
    },
  ],
};

Then, using the gtag plugin, you should be able to hoist the JS that loads the ad code, but show up only on pages where you put a container for it to land in the sidebar. This would take some juggling to manage, or you could swizzle some theme components directly. That leads me to the other option - wrapping it.

With Docusaurus, you also get a lot of the creature comforts that React has to offer (such as Helmet wrappers), which Docusaurus implements as <BrowserOnly>.

You should be able to come up with something so you have somewhat granular control without breaking any upgrade paths, even if you end up writing your own little ad component.

Tim Post
  • 33,371
  • 15
  • 110
  • 174