Page 1 of 1

Function to add scripts in head in frontend mode

Posted: Tue Nov 13, 2018 9:44 am
by nicks
Hello,

I'm trying to write a module, and i need to add js script in the <head> section (though, it would even better if i could add it just before the closing <__body> tag but i fear it might be even harder, right?).

There is this nice function that does it in backend : GetHeaderHTML(), but i can't find a way to do it in frontend?

I see that Gallery module does it, but i can't figure out how. I've also searched in the API guide but can't find a function for it?

Thank you! :)

Re: Function to add scripts in head in frontend mode

Posted: Tue Nov 13, 2018 6:30 pm
by scooper
You'll want to use the contentPostRender event.

In your main module class you can overload the DoEvent function, and if you then detect ContentPostRender you can add whatever extra code you need to.

The code below isn't tested but should insert a string before the closing /html tag:

Code: Select all

function DoEvent( $originator, $eventname, &$params )
	{

	  if ($originator == 'Core' && $eventname == 'ContentPostRender')
		  {
			   $tempcontent=$params['content'];
			   $pos=stripos($tempcontent,"</__html");

			   $code_to_add='<__script__>alert("boop");</__script>';

			   if($pos !== FALSE){
				  			$tempcontent=substr($tempcontent,0,$pos).$code_to_add.substr($tempcontent,$pos);
				  $params['content'] = $tempcontent;
			   }


	   }
	}
( you'll need to remove the extra underscores that the forum is adding before __html and __script__ )

[SOLVED] Function to add scripts in head in frontend mode

Posted: Thu Nov 15, 2018 3:50 pm
by nicks
Thank you scooper, your solution works like a charm.

In addition to create the function in the module class file, i just had to add this in "method.install.php" :

Code: Select all

 $this->AddEventHandler('Core', 'ContentPostRender', false);
And this in "method.uninstall.php" :

Code: Select all

$this->RemoveEventHandler('Core', 'ContentPostRender');
Then, i had to uninstall and install again to see it work!

Re: Function to add scripts in head in frontend mode

Posted: Thu Nov 15, 2018 5:27 pm
by calguy1000
Just a Pro tip or two

a: You could use a hook (2.2+) so that you don't have to add and remove an event handler.

Code: Select all

function InitializeFrontend() {
    \CMSMS\HookManager::add_hook('Core::ContentPostRender',
     [this,'PostRenderHook'] );
}
b: If your module is a plugin module. i.e: called by {MyModule} or {cms_module module=MyModule} then in it's action(s). I would set a member variable, that your event handler can use to conditionally insert the script tags.

Code: Select all

public method PostRenderHook($params) {
    if( $this->myActionCalled ) {
        // content is in $params['content']
        // add my <__script__> tag in there.
    }
    return $params
}