Skip to main content

Variables in drupalSettings get cached

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) {
  window.xx = drupalSettings.pdf_app_height;
  }
 };
})(jQuery, Drupal, drupalSettings);

I am using on the page somewhere else the following javascript code:

alert(xx); 

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.