How to inject javascript from local plugin to specific page in Moodle?

Re: How to inject javascript from local plugin to specific page in Moodle?

by Mark Sharp -
Number of replies: 0
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers

In your local plugin lib.php file, you can add a function to extend the global navigation. You don't actually have to do anything with the navigation, but it's a convenient time in the page loading process to add your javascript. Within that function you could then check the $PAGE->pagetype variable to see the specific page their on (you can get this from the body ID e.g. the home page is #page-site-index, so the pagetype is site-index).

So, if I have a plugin called local_ishatar, in local/ishatar/lib.php I would have:

function local_ishatar_extend_navigation(global_navigation $nav) {
    global $PAGE;
    if ($PAGE->pagetype == 'site-index') {
        // FOR AMD JAVASCRIPTS : https://docs.moodle.org/dev/Javascript_Modules
        $PAGE->requires->js_call_amd('local_ishatar/ishatar', 'init');
        // JQuery plugin : https://docs.moodle.org/dev/jQuery_pre2.9
        $PAGE->requires->jquery_plugin('ishatar', 'local_ishatar');
    }
}

Check the documentation in the links I included in the code, also the readme.txt in the local directory.

When you are creating a mod_ plugin you can hook into the page_init function, but local plugins don't do that, thus hijacking the extend_navigation function.

Average of ratings: Useful (1)