javascriptphpopencartopencart-3opencart-events

Opencart 3.0 - how to add in-line javascript code from catalog controller with event system?


How to add inline js code from controller ?

admin module controller

$this->model_setting_event
     ->addEvent("one_two_three","catalog/view/common/header/before","extension/module/oone_two_three/inject_abc_javascript");

and in catalog module controller

public function inject_abc_javascript(&$route, &$data){
    $code = $this->config->get("module_one_two_three_code");
    $data["scripts"] = "<script>OneTwo.push(function() {
  OneTwo.init({
      appId: $code,
  });});</script>";
}

Is there any way to add inline javascript in OpenCart header?


Solution

  • Yes, you can do it.

    First of all you have an error/typo in addEvent parameters, change oone_two_three to one_two_three.

    Then you need a third parameter for your function:

    public function inject_abc_javascript($route, &$data = false, &$output = false){
        // Before closing tag
        $hook = '</head>';
        $js = '<script>alert("Hello from one_two_three module!");</script></head>';
        $output = str_replace($hook, $js, $output);
    }