0

I have create a hook to alter page funcionality. It's posible invoke javascript function in hook. I test this function but i had this error --> Call to undefined function alert()

      function catalogo_preprocess_node(&$vars)
      {
        alert("hello");
      }

closed as unclear what you're asking by sanzante, Pierre.Vriens, leymannx, mradcliffe, Kevin Oct 11 '18 at 15:20

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • This is by concept a bad idea. PHP is executed on server side, JS is executed client side in the visitors browser, don't do this. Hooks are meant for server side preprocess, there is no point putting a client side JS function in a hook. Use a Drupal behavior instead – Hudri Oct 11 '18 at 11:49
  • Possible duplicate of how to add javascript with #attached and hook_page_alter – mradcliffe Oct 11 '18 at 12:54
  • PHP won't know anything about Javascript functions. You should write AJAX Commands instead and think of things in those terms. But it is generally a bad idea to have Javascript functions that alter page data in the way you're asking. – Kevin Oct 11 '18 at 15:21
1

D7 you can try function drupal_add_js

function hook_preprocess_node(&$vars){
  drupal_add_js(drupal_get_path('theme', 'your_theme') . '/js/my_script.js');
}

D8 You need define one or more (asset) libraries, add a *.libraries.yml file to the root of your theme folder

library_name:
  version: 1.x
  js:
    js/my_script.js: {}

Attaching a library in a preprocess function

function hook_preprocess_node(&$variables){
  $variables['#attached']['library'][] =  'your_theme/library_name';
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.