Score:0

Why is my javascript settings variable empty in Chrome/Edge, but it works in Firefox?

br flag

My javascript file starts like this...

var my_global_var;

(function ($, Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.myBehavior= {
    'attach': function attach(context, settings) {

      console.log(settings); // settings is empty in Chrome and Edge, but it works in Firefox.

...
    
})

(jQuery, Drupal, drupalSettings);

I add the settings in my block's build method...

  /**
   * {@inheritdoc}
   */
  public function build() {

    $states_select = $this->formBuilder->getForm('Drupal\ed_contact\Form\StatesSelect');

    $states_path = '/state_contacts/';

    return [
      '#theme' => 'ed_contact_info',
      '#attached' => [
        'library' => [
          'ed_contact/ed-contact-us',
          'ed_contact/ed-contact-us-map',
        ],
        'drupalSettings' => [
          'ed_contact' => [
            'states_path' => $states_path,
          ]
        ]
      ],
      '#states_path' => $states_path,
      '#states_select' => $states_select,
      'content' => [
        '#cache' => [
          'contexts' => [
            'url.path',
          ],
        ],
      ],
    ];

  }

Libraries file:

ed-contact-us:
  version: 1.x
  js:
    js/ed-contact-us.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

ed-contact-us-map:
  js:
    js/map-config.js: {}
    js/map-interact.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Why might settings be empty in Chrome and Edge? An object is logged to the console, but is empty. In Firefox, settings is populated as expected. I'm following the documentation at https://www.drupal.org/docs/develop/theming-drupal/adding-assets-css-js-to-a-drupal-theme-via-librariesyml#the_process

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.