Html

Article • 11.11.2023 • 8 minute(s) to read

Html

The Html Widget allows you to use HTML and JavaScript directly to create your Widget. Hence, Html fills the gab between existing Widgets, including View Widgets, Form Widgets on one side and Chart Widgets on the other side. Html should be used when the desired functionality cannot be realized with existing Widgets but you do not need the full range of capabilities of Custom Widgets.

If your HTML and JavaScript code should interact with the result of Data Queries, you should use Html Report instead of Html.

The configuration of the Html Widget is done in the Editor shows below Script document. by entering HTML and JavaScript code. Html supports jQuery to implement the JavaScipt code.

Example

This example offers to two input fields and two buttons to interact with Dashboard Parameters:

<script>
// read a Dashboard Parameter
function readParameter() {
    // Get an array of all Dashboard Parameters
    var parameters = aurora.getExistingParamsFromUrl();
    // Get the name of the Dashboard Parameter entered by the user
    var name = document.getElementById("ParameterName").value;
    
    // Iterate over all Dashboard Parameters
    parameters.forEach( function(parameter) {
        // If the name of a Dashboard Parameters matches the name entered by the user ...
        if( parameter.Name == name ) {
            // ... copy the value into the corresponding HTML input field.
            document.getElementById("ParameterValue").value = parameter.Value;
        }
    });
}
// write a Dashboard Parameter
function writeParameter() {
    var name = document.getElementById("ParameterName").value;
    var value = document.getElementById("ParameterValue").value;

    // Get the full content of the browser's address line
    var dashboardUrl = new URL( window.location.href );
    // The Dashboard Parameters are located after the pound sign in the browser's address line
    dashboardUrl.search = window.location.hash.substring(1);
    // Use the URL object to correctly format the Dashboard Parameter
    dashboardUrl.searchParams.set(name, value);
    // Set the updated Dashboard Parameters
    window.location.hash = dashboardUrl.searchParams;
}
</script>

<!-- input field for the Dashboard Parameter name -->
<label>Parameter Name:</label>
<input id="ParameterName" type="text"><br>

<!-- input field for the Dashboard Parameter name -->
<label>Parameter Value:</label>
<input id="ParameterValue" type="text"><br><br>

<!-- buttons to read and write the Dashboard Parameter -->
<button onclick="readParameter()" type="button">Read Dashboard Parameter</button>
<button onclick="writeParameter()" type="button">Write Dashboard Parameter</button>
JavaScript Functions

The usage of jQuery is supported in the in your JavaScript and HTML code. Furthermore, additional JavaScript Functions are available to interact with Novunex Platform specific functionality. These functions are available by calling aurora.functionName(...), where functionName can be one of these functions:

  • apiUrl() - Returns the base URL of the core API

  • clientBaseUrl() - Returns the base URL of the current Account

  • createGuid() - Generates a unique identifier in GUID format

  • debounce( func, wait, immediate ) - Delays the call of the function func by the waiting time specified in wait. wait is interpreted as milliseconds. The wait is only executed if immediate is set to false. If immediate is set to true, func is called immediately.

  • forceLogout() - Forces an logout from the current user session

  • getAccessToken() - Returns the current access token of the authenticated User

  • getApiSubscriptionKey() - Returns the API Subscription key

  • getExistingParamsFromUrl() - Returns all Dashboard Parameters as an array. Each element in the array is an object in the form of { "Name": "ParameterName", "Value": "ParameterValue" }.

  • getFromCache( name ) - Retrieves the value stored in the local cache under the key name. All values are returned as string.

  • getSubscriptionId() - Returns the current Subscription ID

  • hexToRgb( hex ) - Converts the hex color string in hex to a RGB color string, e.g. “03F” to “0033FF”

  • htmlEncode( val ) - Encodes the string val to be in the HTML format, e.g., replacing &#60;, &gt; characters.

  • parseExpression( expressionString, contextIndex ) - Replaces variable names in the expressionString with their value. expressionString has to be a valid Form Control Expression and the variables have to be defined in the current context. contextIndex is deprecated and can be left null.

  • pushToCache( name, value ) - Stores value in the local cache under the key name

  • slugify( text ) - Generates URL slugs, i.e, replaces white spaces within - characters, removes all non-word characters, replaces multiple - with single - characters and trims start and end of string from any white spaces

  • tryParseJson( jsonString ) - Parses jsonString into a JavaScript Object. If the parsing fails, false is returned.

  • showApiError(...) - Generates an error popup and is used used in to handle the failure of the ajax(...) and the upload(...) function. See the documentation of the upload(...) function for an example usage.

  • ajax( settings ) - Executes a core service API call by calling the jQuery.ajax() function of the jQuery framework. settings is passed to the jQuery function. See the documentation of the upload(...) function for an example usage.

  • upload( type, url, data ) - Starts a file upload request, that has to be done in two steps:

    • The file content is uploaded first by calling upload( type, url, data ), where type specifies the HTTP method, url specifies the target of the request and data holds the actual data. The data has to be encoded as multipart/form-data and can hold the content of one or more files, but all files combines must be below the limit of 512MB. To keep the code responsive, it is advised to limit the number of files uploaded each time. upload(...) uploads the file content, creates the file in the file storage of the Novunex Platform and then returns the list of URIs to uniquely identify the newly created files on the Novunex Platform. The list of URIs is sorted in the same order as the list uploaded files.
    • The meta data is uploaded next by calling ajax(...). The meta data can also be uploaded as a list to handle multiple files at the same time, just like the file content before was. Obviously, this list need to be sorted in the same order. The following meta data entries are supported:
      • url - Mandatory entry that establishes the connection between the file content and its meta data. This must be set to the URI returned by upload(...).
      • name - Mandatory file name shown on the Novunex Platform for the uploaded file.
      • category - Optional categorization of the file. Either one of the predefined categories Documents, Images, Spreadsheets, Audio and Videos or a free text entry to define a custom category can be specified.
      • description - Optional free text describing the file.
      • size - Optional file size in bytes

    The example below shows to implementation of a function to upload multiple files at once by using the upload(...) and the ajax(...) functions. This example interacts with the other code the following way:

    • The files are expected to be uploaded by an file selector HTML element. Hence, somewhere on the page in input element of type file is required, like <input type="file" id="myfile" name="myfile">. Then, the example function can be called like
    uploadAll( Array.from( document.getElementById('myfile').files ) );
    
    • Similarly, once the files and the meta data are uploaded successfully, a map of the file names and the ID assigned by the Novunex Platform is composed. This map is then propagated to another function uploadComplete( finishedFiles ). Hence, this function needs to be implemented to handle the successful file upload.
    function uploadAll( inputFiles ) {
        // Prepare the file content as multipart/form-data
        var uploadContent = new FormData();
        inputFiles.forEach( function (file, index) {
            uploadContent.append('file-' + index, file, file.name);
        });
    
        // Upload the file content
        aurora.upload({
            type: 'post',
            url: aurora.apiUrl() + '/file/upload',
            data: uploadContent
        })
        .fail( aurora.showApiError )
        // When the file content has been uploaded successfully, the URIs are returned
        .done( function(uris) {
            // Compile the meta data of the files
            var uploadMetadata = { files: [] };
            inputFiles.forEach( function (file, index) {
                uploadMetadata.files.push({
                    // Mandatory: Link the meta data to the file content via the URL/URI
                    url: uris[index],
                    // Mandatory: Set the name of the file on the Novunex Platform
                    name: file.name,
                    // Optional category
                    category: 'Documents',
                    // Optional description
                    description: 'My file description string.',
                    // Optional file size in bytes
                    size: file.size
                });
            });
              
            // Upload the meta data
            aurora.ajax({
                type: 'put',
                url: aurora.apiUrl() + '/file',
                data: JSON.stringify( uploadMetadata )
            })
            .fail( aurora.showApiError )
            .done( function(fileIds) {
                const finishedFiles = new Map();
                fileIds.forEach( function( fileId, index ) {
                    finishedFiles.set( inputFiles[index].name, fileId );
                });
                // Inform the other components about the successful upload
                uploadComplete( finishedFiles );
            });
        });
    }
    
JavaScript User Information

The user objects offers information about the current User. This information can be accessed with aurora.user.propertyName, where propertyName can be one of the following properties:

  • id - The ID of the current User
  • username - The user name of the current User, i.e., this is the email address of the User
  • accessToken - OAuth access token of the User currently active in this session
  • refreshToken - OAuth refresh token of the current User needed to refresh the accessToken once it expires
  • subscriptionId - The unique ID of the subscription the current User is logged in
  • apiAccessKey - The subscription key for the subscriptionId
  • culture - The culture setting of the current User, e.g., en-US, de-DE, zh-CN, etc.
  • accountGuid - The globally unique ID of the current Account
Samples

Here you find code samples that are often required for HTMLs:

  • Load external JavaScript libraries - This examples loads JavaScript libraries that are not already provided by the Novunex Platform. All JavaScript libraries specified in the array scripts are loaded by this code. After executing this code in your HTML, you can use said JavaScript libraries.
$(function () {
    // Define the libraries to be loaded
    var scripts = [ "https://example.com/libs/mylib.js",
                    "https://domain.com/res/other.js" ];
    function loadScript(scripts) {
        // Iterate over all libraries
        var url = scripts.shift();
        $.getScript(url, function () {
            // As long as there are libraries, load them
            if (scripts.length > 0) {
                loadScript(scripts);
            // If there are no more libraries, call init() to use the libraries
            } else {
                init();
            }
        });
    }
}
In this article