Drupal 8 add inline JavaScript to a page

Posted on 18/02/2020

Separate JS files are good but in certain cases (e.g. tracking scripts) it might be useful to just add a piece of inline code to a specific page.

This can easily be achieved from a custom module by implementing hook_page_attachments(), checking the page you are on and adding the JS code to the HTML head.

Here is the sample code:

  1. /**
  2.  * Implements hook_page_attachments().
  3.  */
  4. function MODULE_NAME_page_attachments(array &$attachments) {
  5.   // You can optionally perform a check to make sure you target a specific page.
  6.   if (\Drupal::routeMatch()->getRouteName() == 'some.route') {
  7.     // Add our JS.
  8.     $attachments['#attached']['html_head'][] = [
  9.       [
  10.         '#tag' => 'script',
  11.         '#attributes' => [
  12.           'type' => 'text/javascript',
  13.         ],
  14.         '#value' => 'console.log("i am here");',
  15.       ],
  16.       'key_for_this_snippet',
  17.     ];
  18.   }
  19. }

See more: