Drupal 9 add inline JavaScript to a page programmatically | Drupal 8

Drupal 9 add inline JavaScript to a page programmatically

Submitted by editor on Thu, 11/26/2020 - 14:15
Question

How to add inline JS script to a page or block programmatically  to drupal 8/9 ?

Method 1 : Form hook_page_attachments

Example:
/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {
  // You can optionally perform a check to make sure you target a specific page.
  if (\Drupal::routeMatch()->getRouteName() == 'some.route') {
    // Add our JS.
    $attachments['#attached']['html_head'][] = [
      [
        '#tag' => 'script',
        '#attributes' => [
          'type' => 'text/javascript',
        ],
        '#value' => \Drupal\Core\Render\Markup::create('console.log("i am here");'),
      ],  'key_for_this_snippet',
    ];
  }
}

Method 2 : Form a controller (Or other renderer array)

Example:
/**
 * Test page
 */
public function aPage() {
$output = [];
// Your page
$output['#attached']['html_head'][] = [
  [
    '#tag' => 'script',
    '#attributes' => [
      'type' => 'text/javascript',
    ],
    '#value' => \Drupal\Core\Render\Markup::create('console.log("i am here");'),
  ],  'key_for_this_snippet',
];
return $output;
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.