Drupal 8 add inline JavaScript to specific page

Profile picture for user a.berramou
Azz-eddine BERRAMOU 26 March, 2020

Separate JS files are good but in certain cases, but sometimes it might be useful to just add a piece of inline JavaScript to a specific page.

To do so from a custom module you can make use of  hook_page_attachment, like the following.

<?php

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$attachments) {
  // Check if this the page you want to add your JS.
  if (\Drupal::routeMatch()->getRouteName() === 'some_module.some_route') {
    
    // Add your JS here.
    $attachments['#attached']['html_head'][] = [
      [
        '#tag'        => 'script',
        '#attributes' => [
          'type' => 'text/javascript',
        ],
        '#value'      => 'console.log("This come from your inline js");',
      ],
      'key_for_this_snippet',
    ];

  }

}

Done ✅ 
Clear cache and Enjoy !