Skip to main content

Notifications

Community site session details

Community site session details

Session Id : Je9Z7twAS0BTosJFfAuA8k
Power Apps - Microsoft Dataverse
Answered

Get Value of Environment Variable using JavaScript

Like (1) ShareShare
ReportReport
Posted on 29 May 2020 10:08:10 by 2

How can I get the value of an Environment Variable using JavaScript?

Categories:
  • Suggested answer
    dmb Profile Picture
    12 on 26 Jul 2024 at 17:57:38
    Get Value of Environment Variable using JavaScript
    You can use these functions:
     
        /**
         * @param variableSchemaName string
         * @returns Returns undefined if env var doesn't exist.
         * Returns the default value if the currently value is null or if no value exists yet.
         * The default value can be null.
         */
        async function getEnvironmentVariableValueUsingFunction(variableSchemaName) {
            try {
                const request = {
                    'DefinitionSchemaName': variableSchemaName,
                    getMetadata: () => {
                        return {
                            boundParameter: null, // undefined = CRUD, null = no table bound, 'entityLogicalName' = if bound to a table
                            operationName: 'RetrieveEnvironmentVariableValue', // action, function or CRUD opetaion name ('Create', 'Retrieve', 'Update', or 'Delete')
                            operationType: 1, // 0 = Action, 1 = Function, 2 = CRUD
                            parameterTypes: {
                                'DefinitionSchemaName': {
                                    typeName: 'Edm.String',
                                    structuralProperty: 1 // 0 = Unknown, 1 = PrimitiveType, 2 =ComplexType, 3 = EnumerationType, 4 = Collection, 5 = EntityType
                                }
                            }
                        }
                    }
                };
                const response = await Xrm.WebApi.online.execute(request);
                const data = await response.json();
                return data.Value;
            } catch (error) {
                console.log(error);
                const baseUrl = Xrm.Utility.getGlobalContext().getClientUrl();
                const methodUrl = `/api/data/v9.2/RetrieveEnvironmentVariableValue(DefinitionSchemaName='${variableSchemaName}')`;
                const response = await fetch(baseUrl + methodUrl);
                const data = await response.json();
                return data.Value;
            }
        }
     
        /**
         * @param variableSchemaName string
         * @returns Returns undefined if env var doesn't exist.
         * Returns the default value if the currently value is null or if no value exists yet.
         * The default value can be null.
         */
        async function getEnvironmentVariableValueUsingQuery(variableSchemaName) {
            const result = await parent.Xrm.WebApi.retrieveMultipleRecords(
                `environmentvariabledefinition`,
                `?$select=displayname,schemaname,defaultvalue` +
                `&$expand=environmentvariabledefinition_environmentvariablevalue($select=value,createdon;$orderby=createdon desc)` +
                `&$filter=(schemaname eq '${variableSchemaName}')`
            );
            const value = result.entities[0]?.environmentvariabledefinition_environmentvariablevalue[0]?.value
            if (value === undefined || value === null) { // keep 0, false, '' as valid values
                return result.entities[0]?.defaultvalue
            } else {
                return value;
            }
        }
  • knunde Profile Picture
    13 on 28 Jun 2024 at 11:19:45
    Re: Get Value of Environment Variable using JavaScript

    "Note: the GUID of the environment variable value will be the same in the different environments if you imported the variable with a solution."

    I know this is an old comment, but at this moment this statment is wrong. The GUID will differ based on the environments, even if you import it as part of a solution. Hopes this could save others some time.

  • Jens Borowy Profile Picture
    5 on 06 Jul 2023 at 07:58:51
    Re: Get Value of Environment Variable using JavaScript

    Here is another example, This code expects an environment variable type JSON, example { "Url":"<URL>", "Login":"<LOGIN>", "PW":"<Password>" }

     

     // Schemaname of the environment variable 
     var connectionDataEnVariable = "<YourEnviromentVariableSchemaName>";
     // var results = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", "?$filter=schemaname eq " + connectionDataEnVariable + "&$select=environmentvariabledefinitionid&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)");
    
     Xrm.WebApi.retrieveMultipleRecords("environmentvariablevalue", "?$select=value&$expand=EnvironmentVariableDefinitionId($select=schemaname)&$filter=EnvironmentVariableDefinitionId/schemaname eq '" + connectionDataEnVariable + "'").then(
     function success(results) {
    
     debugger;
     if (results && results.entities && results.entities.length >= 1) {
     var connectionData = results.entities[0].value;
     }
     else {
     // Die Umgebungsvariable existiert nicht
     alert("Umgebungsvariable " + connectionDataEnVariable + " wurde nicht gefunden.");
     return;
     }
    
     if (connectionData) {
     // Die Umgebungsvariable existiert
     var data = JSON.parse(connectionData);
     var url = data.Url;
     var login = data.Login;
     var pw = data.PW;
    
     console.log("URL: " + url);
     console.log("Login: " + login);
     console.log("Passwort: " + pw);
     }
     },
     function (error) {
     debugger;
     console.log(error.message);
     }
     );

     



  • EricRegnier Profile Picture
    8,714 Most Valuable Professional on 14 Dec 2022 at 08:04:47
    Re: Get Value of Environment Variable using JavaScript

    Thanks @Kuyler! Yup, there’s now an out of the box function for this: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveenvironmentvariablevalue
    cheers

  • Kuyler Profile Picture
    4 on 14 Dec 2022 at 01:33:28
    Re: Get Value of Environment Variable using JavaScript

    To get the correct value use the "RetrieveEnvironmentVariableValueRequest" request with execute.
    Example can found here: https://mytrial365.com/2021/03/15/get-environment-variables-value-using-javascript/

  • Verified answer
    EricRegnier Profile Picture
    8,714 Most Valuable Professional on 10 Mar 2021 at 01:14:01
    Re: Get Value of Environment Variable using JavaScript

    Hi @alanodev, I know this dates a while back but just thought I'll update this thread with the latest code sample to retrieved by environmental variable name:

    async GetEnvironmentVariableValue function (name) {
     let results = await Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", `?$filter=schemaname eq '${name}'&$select=environmentvariabledefinitionid&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)`);
    
     if (!results || !results.entities || results.entities.length < 1) return null;
     let variable = results.entities[0];
     if (!variable.environmentvariabledefinition_environmentvariablevalue || variable.environmentvariabledefinition_environmentvariablevalue.length < 1) return null;
    
     return variable.environmentvariabledefinition_environmentvariablevalue[0].value;
    }

    Note: users will need read privileges to Environment Variable Definition.

    Cheers

  • EricRegnier Profile Picture
    8,714 Most Valuable Professional on 30 May 2020 at 23:03:42
    Re: Get Value of Environment Variable using JavaScript

    Hi @alanodev,

    You can do this with the out-of-the-box client web api script, retrieveRecord.

     

    Xrm.WebApi.retrieveRecord("environmentvariablevalue", <GUID>, "?$select=value").then(successCallback, errorCallback);

     

    Note: the GUID of the environment variable value will be the same in the different environments if you imported the variable with a solution. If you want to fetch by the name and you need to query with EnvironmentVariableDefinition entity.

     

    More info on retrieve: https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrieverecord

    Hope this helps!

     

  • the365bit Profile Picture
    136 on 29 May 2020 at 10:47:09
    Re: Get Value of Environment Variable using JavaScript
    Spoiler (Highlight to read)
     
     

    What kind of environment variable and also where is your javascript sitting, is it a js running in a power apps model driven entity form, canvas app, or something else?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Understanding Microsoft Agents - Introductory Session

Confused about how agents work across the Microsoft ecosystem? Register today!

Warren Belz – Community Spotlight

We are honored to recognize Warren Belz as our May 2025 Community…

Congratulations to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Power Apps - Microsoft Dataverse

#1
SadFox Profile Picture

SadFox 2

Overall leaderboard

Featured topics