Skip to main content

Drupal 9: Injecting JS at the bottom of your page

If you want to inject direct js code before your closing body tag element of your  html page, this is the way to do it.


/**
 * Implements hook_page_bottom().
 */
function pixelthis_page_bottom(array &$page_bottom) {
  
  $sticky_banner_js = '<noscript><a href="//adserver.ADSERVICE.gr/click?webspace=444&amp;dfl=yes"><img src="//adserver.ADSERVICE.gr/banner?webspace=444&amp;dfl=yes&amp;js=no" border="0" width="0" height="0" alt="ADSERVICE" /></a><br /></noscript>
  <script data-server="ADSERVICE|">(function() { var w=window, d=document; if (!window.ADSERVICE)
  d.write(\'<sc\'+\'ript data-ws="444" data-h="adserver.ADSERVICE.gr" data-s="0x0" data-iframe="false" src="https://static.ADSERVICE.gr/ADSERVICE.js" ></sc\'+\'ript>\');
  else ADSERVICE.ws({\'ws\':444,\'s\':\'0x0\',\'h\':\'adserver.ADSERVICE.gr\'});}());</script>';
  

  $overlay_player_banner_js = '<!-- Overlay banner --><noscript><noscript><a href="//adserver.ADSERVICE.gr/click?webspace=33333&amp;dfl=yes"><img src="//adserver.ADSERVICE.gr/banner?webspace=33333&amp;dfl=yes&amp;js=no" border="0" width="0" height="0" alt="ADSERVICE" /></a><br /></noscript>
  <script data-server="ADSERVICE|">(function() { var w=window, d=document; if (!window.ADSERVICE)
  d.write(\'<sc\'+\'ript data-ws="33333" data-h="adserver.ADSERVICE.gr" data-s="0x0" data-iframe="false" src="https://static.ADSERVICE.gr/ADSERVICE.js" ></sc\'+\'ript>\');
  else ADSERVICE.ws({\'ws\':33333,\'s\':\'0x0\',\'h\':\'adserver.ADSERVICE.gr\'});}());</script>';

  $user = \Drupal::currentUser();
  $page_bottom['pixelthis_sticky_banner'] = [
    '#markup' => Markup::create($sticky_banner_js),
    '#cache' => [
      'contexts' => ['user'],
      'tags' => ['user:' . $user->id()],
    ],
  ];
  $page_bottom['overlay_player_banner_js'] = [
    '#markup' => Markup::create($overlay_player_banner_js),
    '#cache' => [
      'contexts' => ['user'],
      'tags' => ['user:' . $user->id()],
    ],
  ];

}

 

hook_page_bottom