1

I have this function from a standalone php script that redirects the user based off the user agent. In the process of merging this into Drupal and the script only needs to execute for a specific content type. Not 100% sure what is the best hook to use: hook_node_presave(), hook_load() or hook_node_view()?

Or should I run this as a template pre-process since this script requires the JS window.location embed?

Part of the code attached:

$web_user_agent = $_SERVER['HTTP_USER_AGENT'];
$current_page = $_SERVER['REQUEST_URI'];

if (!$web_user_agent = '[User Agent Placeholder]') {

    die;

} else {

    echo('<script type="text/javascript">

    if(self==top) {

            window.location = "'. $redirect_url .'";

    } else {

    }
    </script>');
    die;
}
2
  • 1
    Why would you add a script from the backend to unconditionally redirect via javascript? Why would you not redirect from the backend?
    – Clive
    Mar 9 '17 at 13:57
  • What the client wants is okay - its the code needs adjusting.
    – Kevin
    Mar 9 '17 at 14:40
2

It depends on how you want to approach it. Clive's question is still relevant, Javascript redirects are neither great or optimal. However, if it must redirect based on a User Agent, Javascript might be the only option.

I would advise you to do the agent detection on the client side, as the server value may not always be accurate. Your code above won't work.

To load a script based on content type, you can do:

function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'mytype') {
    $variables['#attached']['js'][] = array(args);

    // or

    drupal_add_js('path/to/script.js');
  }
}

Your script itself also needs to be in a closure:

/**
 * @file
 */
(function () {

  "use strict";

  // All the JavaScript for this file.

})();

If jQuery or the Drupal scope is needed:

/**
 * @file
 */
(function ($, Drupal) {

  "use strict";

  // All the JavaScript for this file.

})(jQuery, Drupal);

See the docs page for more:

1
  • The moment you turn on any sort of caching that code in the OP is not going to work for UA detection. Plus it has an error in it, the if condition will always be TRUE because you are setting the variable instead of comparing it.
    – Kevin
    Mar 9 '17 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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