W3cubDocs

/Cordova 8

Hooks

Introduction

Cordova Hooks represent special scripts which could be added by application and plugin developers or even by your own build system to customize cordova commands.

Cordova hooks allow you to perform special activities around cordova commands. For example, you may have a custom tool that checks for code formatting in your javascript file. And, you would like to run this tool before every build. In such a case, you could use a 'before_build' hook and instruct the cordova run time to run the custom tool to be invoked before every build.

Hooks might be related to your application activities such as before_build, after_build, etc. Or, they might be related to the plugins of your application. For example, hooks such as before_plugin_add, after_plugin_add, etc applies to plugin related activities. These hooks can be associated with all plugins within your application or be specific to only one plugin.

Cordova supports the following hook types:

Hook Type Associated Cordova Commands Description
before_platform_add cordova platform add To be executed before and after adding a platform.
after_platform_add
before_platform_rm cordova platform rm To be executed before and after removing a platform.
after_platform_rm
before_platform_ls cordova platform ls To be executed before and after listing the installed and available platforms.
after_platform_ls
before_prepare cordova prepare
cordova platform add
cordova build
cordova run
To be executed before and after preparing your application.
after_prepare
before_compile cordova compile
cordova build
To be executed before and after compiling your application.
after_compile
before_deploy cordova emulate
cordova run
To be executed before deploying your application.
before_build cordova build To be executed before and after building your application.
after_build
before_emulate cordova emulate To be executed before and after emulating your application.
after_emulate
before_run cordova run To be executed before and after running your application.
after_run
before_serve cordova serve To be executed before and after serving your application.
after_serve
before_clean cordova clean To be executed before and after cleaning your application.
after_clean
pre_package N/A Applicable to Windows 8 and Windows Phone only. This hook is deprecated.
before_plugin_add cordova plugin add To be executed before and after adding a plugin.
after_plugin_add
before_plugin_rm cordova plugin rm To be executed before and after removing a plugin.
after_plugin_rm
before_plugin_ls cordova plugin ls To be executed before and after listing the plugins in your application.
after_plugin_ls
before_plugin_search cordova plugin search To be executed before and after a plugin search.
after_plugin_search
before_plugin_install cordova plugin add To be executed before and after installing a plugin (to the platforms). Plugin hooks in plugin.xml are executed for a plugin being installed only
after_plugin_install
before_plugin_uninstall cordova plugin rm To be executed before uninstalling a plugin (from the platforms).Plugin hooks in plugin.xml are executed for a plugin being installed only

Ways to define hooks

Config.xml

Hooks could be defined in project's config.xml using <hook> elements, for example:

<hook type="before_build" src="scripts/appBeforeBuild.bat" />
<hook type="before_build" src="scripts/appBeforeBuild.js" />
<hook type="before_plugin_install" src="scripts/appBeforePluginInstall.js" />

<platform name="android">
    <hook type="before_build" src="scripts/wp8/appAndroidBeforeBuild.bat" />
    <hook type="before_build" src="scripts/wp8/appAndroidBeforeBuild.js" />
    <hook type="before_plugin_install" src="scripts/wp8/appWP8BeforePluginInstall.js" />
    ...
</platform>

<platform name="windows">
    <hook type="before_build" src="scripts/windows/appWinBeforeBuild.bat" />
    <hook type="before_build" src="scripts/windows/appWinBeforeBuild.js" />
    <hook type="before_plugin_install" src="scripts/windows/appWinBeforePluginInstall.js" />
    ...
</platform>

Plugin hooks (plugin.xml)

As a plugin developer you can define hook scripts using <hook> elements in a plugin.xml like that:

<hook type="before_plugin_install" src="scripts/beforeInstall.js" />
<hook type="after_build" src="scripts/afterBuild.js" />

<platform name="android">
    <hook type="before_plugin_install" src="scripts/androidBeforeInstall.js" />
    <hook type="before_build" src="scripts/androidBeforeBuild.js" />
    ...
</platform>

before_plugin_install, after_plugin_install, before_plugin_uninstall plugin hooks will be fired exclusively for the plugin being installed/uninstalled.

Via /hooks directory (Deprecated)

To execute custom action when corresponding hook type is fired, use hook type as a name for a subfolder inside 'hooks' directory and place you script file here, for example:

# script file will be automatically executed after each build
hooks/after_build/after_build_custom_action.js

When using these hooks, they will always be run as executable files, not as loadable JavaScript modules.

Remember: Make your scripts executable in this case.

Note: this method is considered deprecated in favor of the hook elements in config.xml and plugin.xml.

Order of Hooks execution

Based on Hooks Definition

Hook scripts could be defined by adding them to the special predefined folder (/hooks) or via configuration files (config.xml and plugin.xml) and run serially in the following order:

  • Application hooks from /hooks;
  • Application hooks from config.xml;
  • Plugin hooks from plugins/.../plugin.xml.

Based on the Internal order of execution

The internal order of execution of hooks is fixed.

Example 1 (cordova platform add)

If there are hooks associated with before_platform_add, after_platform_add, before_prepare, after_prepare, before_plugin_install and after_plugin_install (and assuming you have one plugin installed on your project), adding a new platform will execute the hooks in the following order:

before_platform_add
    before_prepare
    after_prepare
    before_plugin_install
    after_plugin_install
after_platform_add
Example 2 (cordova build)

If there are hooks associated with before_prepare, after_prepare, before_compile, after_compile, before_build and after_build - running a build command will execute the hooks in the following order:

before_build
    before_prepare
    after_prepare
    before_compile
    after_compile
after_build

Script Interface

Windows Quirks

If you are working on Windows, and in case your hook (Javascript/Non-Javascript)scripts aren't bat files (which is recommended, if you want your scripts to work in non-Windows operating systems) Cordova CLI will expect a shebang line as the first line for it to know the interpreter it needs to use to launch the script. The shebang line should match the following example:

#!/usr/bin/env [name_of_interpreter_executable]

Javascript

If you are writing hooks using Node.js you should use the following module definition:

module.exports = function(context) {
    ...
}

context object contains hook type, executed script full path, hook options, command-line arguments passed to Cordova and top-level "cordova" object of the following format:

{
  "hook": "before_plugin_install",
  "scriptLocation": "c:\\script\\full\\path\\appBeforePluginInstall.js",
  "cmdLine": "The\\exact\\command\\cordova\\run\\with arguments",
  "opts": {
    "projectRoot":"C:\\path\\to\\the\\project",
    "cordova": {
      "platforms": ["android"],
      "plugins": ["plugin-withhooks"],
      "version": "0.21.7-dev"
    },
    "plugin": {
      "id": "plugin-withhooks",
      "pluginInfo": {
        ...
      },
      "platform": "android",
      "dir": "C:\\path\\to\\the\\project\\plugins\\plugin-withhooks"
    }
  },
  "cordova": {...}
}

context.opts.plugin object will only be passed to plugin hooks scripts.

You can also require additional Cordova modules in your script using context.requireCordovaModule in the following way:

var Q = context.requireCordovaModule('q');

You can make your scipts async using Q:

module.exports = function(context) {
    var Q = context.requireCordovaModule('q');
    var deferral = new Q.defer();

    setTimeout(function(){
      console.log('hook.js>> end');
    deferral.resolve();
    }, 1000);

    return deferral.promise;
}

Note: new module loader script interface is used for the .js files defined via config.xml or plugin.xml only. For compatibility reasons hook files specified via /hooks folders are run via Node child_process spawn, see 'Non-javascript' section below.

Non-javascript

Non-javascript scripts are run via Node child_process spawn from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:

Environment Variable Name Description
CORDOVA_VERSION The version of the Cordova-CLI.
CORDOVA_PLATFORMS Comma separated list of platforms that the command applies to (e.g: android, ios).
CORDOVA_PLUGINS Comma separated list of plugin IDs that the command applies to (e.g: cordova-plugin-file-transfer, cordova-plugin-file).
CORDOVA_HOOK Path to the hook that is being executed.
CORDOVA_CMDLINE The exact command-line arguments passed to cordova (e.g: cordova run ios --emulate).

If a script returns a non-zero exit code, then the parent cordova command will be aborted.

Note: we highly recommend writing your hooks using Node.js so that they are cross-platform, see Javascript section above.

Sample Usage

This sample demonstrates Cordova hooks usage to trace to the console output the size of generated .apk file for Android platform.

Create blank Cordova app and add the following definition to config.xml to tell Cordova to run afterBuild.js script after each platform build.

<hook type="after_build" src="scripts/afterBuild.js" />

Create scripts/afterBuild.js file and add the following implementation. We use async version of fs.stat method to demonstrate how async functionality could be done via hooks.

module.exports = function(ctx) {
    // make sure android platform is part of build
    if (ctx.opts.platforms.indexOf('android') < 0) {
        return;
    }
    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        deferral = ctx.requireCordovaModule('q').defer();

    var platformRoot = path.join(ctx.opts.projectRoot, 'platforms/android');
    var apkFileLocation = path.join(platformRoot, 'build/outputs/apk/android-debug.apk');

    fs.stat(apkFileLocation, function(err,stats) {
        if (err) {
                deferral.reject('Operation failed');
        } else {
            console.log('Size of ' + apkFileLocation + ' is ' + stats.size +' bytes');
            deferral.resolve();
        }
    });

    return deferral.promise;
};

Parameter ctx in example above is passed by Cordova and represents execution context such as script full path, target platform, command-line arguments, etc and also exposes additional helper functionality. See Script Interface section above for more details.

You can now add android platform and execute build.

cordova platform add android
..
cordova build
..
Size of path\to\app\platforms\android\build\outputs\apk\android-debug.apk is 1821193 bytes

More good usage examples could be found in Three Hooks Your Cordova Phone Gap Project needs

© 2012–2018 The Apache Software Foundation
Licensed under the Apache License 2.0.
https://cordova.apache.org/docs/en/8.x/guide/appdev/hooks/index.html