I am using the value of a field in the page as a variable. I am trying to use it in the page somewhere else but I think that there is a problem with the cache because the value is sometimes available and sometimes not.

I have the following:

$elements['#attached']['drupalSettings']['pdf_app_height'] = $password;

and then in a .js file I have:

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

 Drupal.behaviors.pdf_appAccessData = {

attach: function (context) {
 value = drupalSettings.pdf_app_height;

  window.xx = drupalSettings.pdf_app_height;
})(jQuery, Drupal, drupalSettings);

The alert (value) always shows the right value but I am using on the page somewhere else the following javascript code:


Sometimes it is showing the right value and sometimes undefined. Any ideas?

I have seen the answer if we are talking about configuration changes (How do I avoid having to clear the cache when changing a module configuration parameter?) but I don't know how to use it here.

  • Are you sure that the times it sets undefined on JS has actually a value on the server side? On the other hand #attached is a render array key so if element gets cached you will get the same attached settings every time since the actual element is not rendered again until it's cache is invalidated.
    – d70rr3s
    Commented Jan 15, 2020 at 13:19
  • What function are you doing $elements['#attached']['drupalSettings']['pdf_app_height'] = $password; in?
    – Leigh
    Commented Jan 15, 2020 at 13:23
  • Please check my new edit..The alert works always inside of the attach but not always when called from outside.. Commented Jan 15, 2020 at 13:42
  • You mean if you call alert(drupalSettings.pdf_app_height); outside of the behavior you get sometimes undefined but called inside the behavior always returns the proper value? Do you have big_pipe module enabled? If so take in mind that JS are "streamed" to the browser so JS called inside the template could and probably executed first that one attached through the render pipeline.
    – d70rr3s
    Commented Jan 15, 2020 at 14:27
  • Yes I see it is enabled by default in drupal8 what do you suggest then? I actually try to call it from an iframe in the same page Commented Jan 15, 2020 at 16:00


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.