简体   繁体   中英

How can I run javascript after user login in joomla 3?

I try to use this function in a plugin, but is not working, maybe because javascript doesn't have time to execute after login an I end up redirected to homepage

 public function onUserAfterLogin($text) {
    $app = JFactory::getApplication();
    
    $document = JFactory::getDocument();
    $document->addScriptDeclaration('document.addEventListener("message", function(event) {
          alert("test");
        });
    ');
} 

I have tried with even with echo

echo '<script type="text/javascript">
   alert("test");
</script>';

One quick method is to redirect the user on login (this can be done at the menu item level) to a static HTML page/or a dynamic PHP page (depending on your needs) that contain the JavaScript code, and that page can then redirect to the page of your choice after firing the JS code.

thank you for the sugestion, but I've used the function in joomla onAfterRender() , and inside the function you can do this:

//This event is triggered after the framework has rendered the application.
//When this event is triggered the output of the application is available in the response buffer.
public function onAfterRender() {
$app = JFactory::getApplication();
$user_id = JFactory::getUser()->id; // NOT 0
$is_guest = JFactory::getUser()->guest; 
if ($user_id !== 0 && $is_guest !== 'guest') {
  $myJScript = 'alert("Test");';
  // retrieve all the response as an html string
  $html = $app->getBody();
  // Search and replace tag </body> with the new script+</body>
  $html = str_replace('</body>','<script type="text/javascript">' . $myJScript . '</script></body>', $html);
  // override the original response
  $app->setBody($html);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM