Add inline Javascript code in Drupal 9

26 / May / 2023 by priya.chowdhury 0 comments

In our Drupal projects, we have requirements to add some kind of inline javascript code, like adding GTM script. This can be in the page header or page bottom as per requirements. So in the blog, we will see how we can achieve this by both methods.

Drupal provides hooks to do this in a proper way. To add the inline javascript code in the page header, we can use hook_page_attachments(), and for the page bottom, we can use hook hook_page_bottom()

Let’s understand this with examples.

Method 1: Add inline Javascript code in page header

/**
* 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(“This” is my javascript code);’),
],  'key_for_this_snippet',
];
}
}

Method 2: Add inline Javascript code in page bottom

/**
* Implements hook_page_bottom().
*/
function MYMODULE_page_bottom(array &$page_bottom) {
$user = \Drupal::currentUser();
$page_bottom['pixelthis_sticky_banner'] = [
'#markup' => \Drupal\Core\Render\Markup::create('console.log(“This” is my javascript code);’),
'#cache' => [
'contexts' => ['user'],
'tags' => ['user:' . $user->id()],
],
];
}

You can add this JS script for global or page specific as per your requirements. For that, add conditions before rendering the markup. Also, we can add the same by using route and controller.

If you still have questions, comment and join the discussion. I will be adding different ways in the upcoming blogs. Stay tuned.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *