Search code examples
xpages-ssjs

XPages: Can an SSJS function be reused on a single XPage without putting it in a library?


I have a ssjs function that is only called a couple of times in a self-contained XPages custom control.

Is there a way to keep this function in the XPage/CustomControl itself and call it directly without storing it in a separate javascript library?


Solution

  • This is how server-side javascript can be made available everywhere in the XPage (or Custom Control) without the need to place it in a Script Library:

    Right under <xp:view>:

    <xp:this.resources>
        <xp:script clientSide="false">
            <xp:this.contents>
                <![CDATA[${javascript:
                    var testA = "123";
                    function testB(){
                        return "123";
                    }
                    return true;
                }]]>
            </xp:this.contents>
        </xp:script>
    </xp:this.resources>
    

    Notes:

    • It is necessary that the code ends with something like return true otherwise the server generates an error parsing js code.
    • The <xp:view> resources get loaded in the order they are listed in the XML source. If you have code that depends on other code, make sure to order them properly.
    • My previous answer (below) has the complication that quotations and new lines must be escaped, and it doesn't help that the javascript engine shipped with Domino 9 is outdated (ES ver 3).

    Previous answer from 2017:

    Add a ComputedField (e.g. name it 'local_ssjs') and let it generate the desired shared js code as a string value.

    E.g.: "function returnFour(){retrun (4)};"

    In your event, obtain the shared code and use the eval() function to include it.

    var sharedCode = getComponent("local_ssjs").getValue(); eval(sharedCode); var xFour = returnFour();

    Even if the computed field only contains function definitions, this works ok.