Search code examples
javascriptmoduleprestashopadmincall

Use JS file for a Prestashop's module


I can't use a JS file for my module's admin configuration in Prestashop. I tried every docs and advises I read here and there but can't do anything with them.

I used the displayBackOfficeHeader hook as you can see here :

public function install()
    {
        if (Shop::isFeatureActive()) {
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        
        if (!parent::install() ||
        !$this->registerHook('leftColumn') ||
        !$this->registerHook('header') ||
        !$this->registerHook('displayBackOfficeHeader') ||
        !Configuration::updateValue('MM_CUSTOM_PAGENAME', 'Test') ||
        // CREATE MM_CUSTOM_TEMPLATE FOR EVERY CATEGORIES ADDED
        $this->defineCategorieTableName() ||
        !Configuration::updateValue('MM_CUSTOM_FONT', 'Test') ||
        !Configuration::updateValue('MM_CUSTOM_CATEGORIE', 'Test')
        ) {
            return false;
        }
        
        return true;
    }

And created a simple function :

 public function hookDisplayBackOfficeHeader()
    {
        $this->context->controller->addJS($this->_path.'views/js/configure.js');
    }

The <script type="text/javascript" src="/modules/mm_custom/views/js/configure.js"></script> is well added in the tag up there.

But if I type this in the configure.js file :

console.log('hello');
const categories = document.querySelectorAll('.cat')
console.log(categories);

I get this in the console :

console screenshot

As if it has no access to the html down there we can see in the dev tool. I'm not getting out of this trouble for 2 days...

Thanks to help guys ;)

EDIT: If I put the <script src: ....> in the .tpl itself, it works fine. But I won't have access to elements in an automatically generated form on the same front page (but not in the .tpl I created)


Solution

  • Maybe try with:

    document.addEventListener("DOMContentLoaded", function() {
      // code...
    });