logo

NJP

[HowTo] Constructor (initialize) for Client Callable Script Includes

Import · May 19, 2022 · article

Maybe you don't know it, but it is actually possible to have a initialize function for client callable script includes. The default-initialize vanishes once you hit the 'Client callable' checkbox, but you can add this function to make it work again:

initialize: function(request, responseXML, gc) {
    global.AbstractAjaxProcessor.prototype.initialize.apply(this, arguments);

    this.myVar = 'myValue';
}

Keep in mind thought that it is not possible to use any (meaningfull) parameters for your Script Include calls (how would you even be able to transmit those in a GlideAjax call right?). If you had a regular client callable script include that you were already using server side as well, then you wouldn't have had any initialize-parameters anyways...

Full example:

/* global global, Class */
/* eslint no-undef: "error" */
var MYSCRIPTINCLUDE = Class.create();
MYSCRIPTINCLUDE.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    initialize: function(request, responseXML, gc) {
        global.AbstractAjaxProcessor.prototype.initialize.apply(this, arguments);

        this.myArg = 'myValue';
    },

    // the result of this call will be casted to string anyways,
    // therefore we use a JSON for your result object
    MYFUNC: function() {
        var param = this.getParameter('MYPARAM');
        return JSON.stringify({
            param: param + this.myArg // echo just for demonstration purposes
        });
    },

    type: 'MYSCRIPTINCLUDE'
});
View original source

https://www.servicenow.com/community/developer-articles/howto-constructor-initialize-for-client-callable-script-includes/ta-p/2318063