Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Drupal 9 add inline JavaScript to a page programmatically

By editor , 26 November, 2020
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;
}

Tags

  • Drupal 8
  • Code
  • JavaScript
Add JavaScript to a module

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer