I'm creating a custom module to execute some JS AFTER the cache is cleared. Here is the structure of the module:
Module -> flush.info.yml
name: Flush
type: module
description: A very important module.
package: Custom
version: 1.0
core_version_requirement: ^8 || ^9
Module -> flush.libraries.yml
flush:
version: 1.x
js:
js/flush.js: {}
dependencies:
- core/jquery
- core/drupalSettings
Module -> flush.module
<?php
use Drupal\Core\Form\FormStateInterface;
/**
* Implementation of hook_cache_flush()
*/
function flush_cache_flush() {
\Drupal::state()->set('flush_cache_cleared', TRUE);
}
function flush_page_attachments(array &$attachments) {
if (\Drupal::state()->get('flush_cache_cleared')) {
$attachments['#attached']['library'][] = 'flush/flush';
\Drupal::state()->set('flush_cache_cleared', FALSE);
}
}
Module -> JS -> flush.js
(function ($, Drupal, drupalSettings) {
'use strict';
Drupal.behaviors.flush = {
/**
* Drupal attach behavior.
*/
attach: function (context, settings) {
this.settings = this.getSettings(settings);
alert("flush!");
console.log ("Hello World");
},
};
})(jQuery, Drupal, drupalSettings);
Both functions in flush.module work properly, however the JS that is #attached which is simply supposed to use an alert() never runs. I believe the issue is related to this line specifically : $attachments['#attached']['library'][] = 'flush/flush';
Is there something obvious I'm doing wrong? I used page_attachments as the method to attach the JS because it does not necessarily have to be associated with a specific part of the page, or a render array, etc. Please let me know if you have any potential ideas as to what the issue could be, thanks!