Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Enabling Application Insights via Tag Management System #1462

Closed
stephen-price-jb opened this issue Jan 21, 2021 · 7 comments
Closed
Labels
closed Automatically Closed Issue/PR p3 snippet Snippet update required or suggested stale

Comments

@stephen-price-jb
Copy link

stephen-price-jb commented Jan 21, 2021

Hi, I'm having some problems with trying to enable Application Insights via Google Tag Manager (GTM). I have taken the sample snippet from the readme page but am getting errors about ES6 syntax. Below is a screenshot of from GTM:
image

Here is the snippet I am using:

<script type="text/javascript">
!function(T,l,y){var S=T.location,u="script",k="instrumentationKey",D="ingestionendpoint",C="disableExceptionTracking",E="ai.device.",I="toLowerCase",b="crossOrigin",w="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"4",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[I](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,p,l,u;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][I]()]=i[1])}if(!e[D]){var r=e.endpointsuffix,o=r?e.location:null;e[D]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[k]||d[k]||"",p=s[D],l=p?p+"/v2/track":config.endpointUrl,(u=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=l,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),u.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,l)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:w,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(w,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(u,l))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(u);n.src=h;var e=y[b];return!e&&""!==e||"undefined"==n[b]||(n[b]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(u)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[C]&&!0!==s[C]){method="onerror",t(["_"+method]);var c=T[method];T[method]=function(e,t,n,a,i){var r=c&&c(e,t,n,a,i);return!0!==r&&m["_"+method]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);(T[t]=n).queue&&0===n.queue.length&&n.trackPageView({})}(window,document,{
src: "https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js", // The SDK URL Source
//name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
//ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
//useXhr: 1, // Use XHR instead of fetch to report failures (if available),
//crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag 
cfg: { // Application Insights Configuration
    instrumentationKey: {{RLT - instrumentationKey}},
    disableAjaxTracking: true
}});
</script>

We currently have the older snippet which works. I have included it below for reference:

<script type="text/javascript">
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var s="Track"+r[0];if(n("start"+s),n("stop"+s),n("setAuthenticatedUserContext"),n("clearAuthenticatedUserContext"),n("flush"),!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("_"+(r="onerror"));var o=a[r];a[r]=function(e,n,i,a,s){var c=o&&o(e,n,i,a,s);return!0!==c&&t["_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:s}),c},e.autoExceptionInstrumented=!0}return t}(
{
  instrumentationKey:{{RLT - instrumentationKey}},
  disableAjaxTracking: true
}
);window[aiName]=aisdk,aisdk.queue&&0===aisdk.queue.length&&aisdk.trackPageView({});
</script>

Any help would be greatly appreciated.

Thanks Steve

@MSNev
Copy link
Collaborator

MSNev commented Jan 21, 2021

Hi, the snippet doesn't contain any ES6 syntax (it's actually ES3), however, I did notice that you are using version 4 (see the sv:"4") in the snippet which does have a bug that we recently fixed (#1402).

Can you try updating based on the current version (sv:"5") on the readme
https://github.com/microsoft/ApplicationInsights-JS#snippet-setup-ignore-if-using-npm-setup

It also contains a new "onInit: configuration

@stephen-price-jb
Copy link
Author

Thanks @MSNev I have updated the snippet as follows:

<script type="text/javascript">
!function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),l.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(k)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
    instrumentationKey:{{RLT - instrumentationKey}},
    disableAjaxTracking: true
}});
</script>

Still getting the same error reported from Google.
image

@MSNev
Copy link
Collaborator

MSNev commented Jan 22, 2021

Ok, this is going to take some more digging and using the minified snippet is not useful. So...
Can you try using the full unminified snippet code that way we should get the actual line that it's complaining about.

The code for the unminified snippet can be found here (all 327 lines of it)
https://github.com/microsoft/ApplicationInsights-JS/blob/master/AISKU/snippet/snippet.js

@stephen-price-jb
Copy link
Author

Using the unminified snippet, I get the following errors:
image

And here is the code:

<script type="text/javascript">
(function (win, doc, snipConfig) {
    var locn = win.location;
    var helpLink = "https://go.microsoft.com/fwlink/?linkid=2128109";
    var scriptText = "script";
    var strInstrumentationKey = "instrumentationKey";
    var strIngestionendpoint = "ingestionendpoint";
    var strDisableExceptionTracking = "disableExceptionTracking";
    var strAiDevice = "ai.device.";
    var strAiOperationName = "ai.operation.name";
    var strAiSdkVersion = "ai.internal.sdkVersion";
    var strToLowerCase = "toLowerCase";
    var strEmpty = "";
    var strUndefined = "undefined";
    var strCrossOrigin = "crossOrigin";

    var strPostMethod = "POST";
    var sdkInstanceName = "appInsightsSDK";         // required for Initialization to find the current instance
    var aiName = snipConfig.name || "appInsights";  // provide non default instance name through snipConfig name value
    if (snipConfig.name || win[sdkInstanceName]) {
        // Only set if supplied or another name is defined to avoid polluting the global namespace
        win[sdkInstanceName] = aiName;
    }
    var aiSdk = win[aiName] || (function (aiConfig) {
        var loadFailed = false;
        var handled = false;
        var appInsights = {
            initialize: true,   // initialize sdk on download
            queue: [],
            sv: "5",            // Track the actual snippet version for reporting.
            version: 2.0,       // initialization version, if this is not 2.0 the previous scripts fail to initialize
            config: aiConfig
        };
        function _parseConnectionString() {
            var fields = {};
            var connectionString = aiConfig.connectionString;
            if (connectionString) {
                var kvPairs = connectionString.split(";");
                for (var lp = 0; lp < kvPairs.length; lp++) {
                    var kvParts = kvPairs[lp].split("=");
    
                    if (kvParts.length === 2) { // only save fields with valid formats
                        fields[kvParts[0][strToLowerCase]()] = kvParts[1];
                    }
                }
            }

            // apply the default endpoints
            if (!fields[strIngestionendpoint]) {
                // use endpoint suffix where overrides are not provided
                var endpointSuffix = fields.endpointsuffix;
                // Only fetch the location if a suffix was supplied
                var fLocation = endpointSuffix ? fields.location : null;
                fields[strIngestionendpoint] = "https://" + (fLocation ? fLocation + "." : strEmpty) + "dc." + (endpointSuffix || "services.visualstudio.com");
            }

            return fields;
        }

        function _sendEvents(evts, endpointUrl) {
            if (JSON) {
                var sender = win.fetch;
                if (sender && !snipConfig.useXhr) {
                    sender(endpointUrl, { method:strPostMethod, body: JSON.stringify(evts), mode:"cors"});
                } else if (XMLHttpRequest) {
                    // IE doesn't support fetch and private clouds may only be using IE
                    var xhr = new XMLHttpRequest();
                    xhr.open(strPostMethod, endpointUrl);
                    xhr.setRequestHeader("Content-type", "application/json");
                    xhr.send(JSON.stringify(evts));
                }
            }
        }

        function _reportFailure(targetSrc) {
            var conString = _parseConnectionString();
            var iKey = conString[strInstrumentationKey] || aiConfig[strInstrumentationKey] || strEmpty;
            var ingest = conString[strIngestionendpoint];
            var endpointUrl = ingest ? ingest + "/v2/track" : aiConfig.endpointUrl; // only add /v2/track when from connectionstring

            var message = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)";
            var evts = [];
            evts.push(_createException(iKey, message, targetSrc, endpointUrl));
            evts.push(_createInternal(iKey, message, targetSrc, endpointUrl));

            _sendEvents(evts, endpointUrl);
        }

        // Gets the time as an ISO date format, using a function as IE7/8 doesn't support toISOString
        function _getTime() {
            var date = new Date();
            function pad(num) {
                var r = strEmpty + num;
                if (r.length === 1) {
                    r = "0" + r;
                }

                return r;
            }

            return date.getUTCFullYear()
                + "-" + pad(date.getUTCMonth() + 1)
                + "-" + pad(date.getUTCDate())
                + "T" + pad(date.getUTCHours())
                + ":" + pad(date.getUTCMinutes())
                + ":" + pad(date.getUTCSeconds())
                + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5)
                + "Z";            
        }

        function _createEnvelope(iKey, theType) {
            var tags = {};
            var type = "Browser";
            tags[strAiDevice + "id"] = type[strToLowerCase]();
            tags[strAiDevice + "type"] = type;
            tags[strAiOperationName] = locn && locn.pathname || "_unknown_";
            tags[strAiSdkVersion] = "javascript:snippet_" + (appInsights.sv || appInsights.version);

            return {
                time: _getTime(),
                iKey: iKey,
                name: "Microsoft.ApplicationInsights." + iKey.replace(/-/g, strEmpty) + "." + theType,
                sampleRate: 100,
                tags: tags,
                data: {
                    baseData: {
                        ver: 2
                    }
                }
            };
        }

        function _createInternal(iKey, message, targetSrc, endpointUrl) {
            var envelope = _createEnvelope(iKey, "Message");
            var data = envelope.data;
            data.baseType = "MessageData";
            var baseData = data.baseData;
            baseData.message = "AI (Internal): 99 message:\"" + (message + " (" + targetSrc + ")").replace(/\"/g, strEmpty) + "\"";
            baseData.properties = {
                endpoint: endpointUrl
            };

            return envelope;
        }

        function _createException(iKey, message, targetSrc, endpointUrl) {
            var envelope = _createEnvelope(iKey, "Exception");
            var data = envelope.data;
            data.baseType = "ExceptionData";
            data.baseData.exceptions = [{
                typeName: "SDKLoadFailed",
                message: message.replace(/\./g, "-"),  // Replacing '.' characters as it causes the portal to hide the start of the message in the summary
                hasFullStack: false,
                stack: message + "\nSnippet failed to load [" + targetSrc + "] -- Telemetry is disabled\nHelp Link: " + helpLink + "\nHost: " + (locn && locn.pathname || "_unknown_") + "\nEndpoint: " + endpointUrl,
                parsedStack: []
            }];

            return envelope;
        }
    
        // Assigning these to local variables allows them to be minified to save space:
        var targetSrc = aiConfig.url || snipConfig.src;
        if (targetSrc) {
            function _handleError(evt) {
                loadFailed = true;
                appInsights.queue = []; // Clear the queue
                if (!handled) {
                    handled = true;
                    _reportFailure(targetSrc);
                }
            }

            function _handleLoad(evt, isAbort) {
                if (!handled) {
                    // IE10, Opera calls loaded before the script is processed.
                    // so delaying to give the script a chance to be processed
                    setTimeout(function() {
                        if (isAbort || !appInsights.core) {
                            _handleError();
                        }
                    }, 500);
                }
            }

            function _createScript() {
                var scriptElement = doc.createElement(scriptText);
                scriptElement.src = targetSrc;

                // Allocate Cross origin only if defined and available
                var crossOrigin = snipConfig[strCrossOrigin];
                if ((crossOrigin || crossOrigin === "") && scriptElement[strCrossOrigin] != strUndefined) {
                    scriptElement[strCrossOrigin] = crossOrigin;
                }
            
                scriptElement.onload = _handleLoad;
                scriptElement.onerror = _handleError;

                // Some browsers support onload while others onreadystatechange and others both
                scriptElement.onreadystatechange = function (evt, isAbort) {
                    if (scriptElement.readyState === "loaded" || scriptElement.readyState === "complete") {
                        _handleLoad(evt, isAbort);
                    }
                };                

                return scriptElement;
            }

            var theScript = _createScript();
            if (snipConfig.ld < 0) {
                // if user wants to append tag to document head, blocking page load
                var headNode = doc.getElementsByTagName("head")[0];
                headNode.appendChild(theScript);
            } else {
                setTimeout(function () {
                    // Attempts to place the script tag in the same location as the first script on the page
                    doc.getElementsByTagName(scriptText)[0].parentNode.appendChild(theScript);
                }, snipConfig.ld || 0);
            }
        }
    
        // capture initial cookie
        try {
            appInsights.cookie = doc.cookie;
        } catch (e) { }
    
        function _createMethods(methods) {
            while (methods.length) {
                (function (name) {
                    // Define a temporary method that queues-up a the real method call
                    appInsights[name] = function () {
                        // Capture the original arguments passed to the method
                        var originalArguments = arguments;
                        if (!loadFailed) { // If we have detected that the main script failed to load then stop queuing events that will never be processed
                            // Queue-up a call to the real method
                            appInsights.queue.push(function () {
                                // Invoke the real method with the captured original arguments
                                appInsights[name].apply(appInsights, originalArguments);
                            });
                        }
                    };
                })(methods.pop());
            }
        }

        var track = "track";
        var trackPage = "TrackPage";
        var trackEvent = "TrackEvent";
        _createMethods([track + "Event", 
            track + "PageView", 
            track + "Exception", 
            track + "Trace", 
            track + "DependencyData", 
            track + "Metric", 
            track + "PageViewPerformance",
            "start" + trackPage, 
            "stop" + trackPage,
            "start" + trackEvent, 
            "stop" + trackEvent,
            "addTelemetryInitializer", 
            "setAuthenticatedUserContext", 
            "clearAuthenticatedUserContext", 
            "flush"]);
    
        // expose SeverityLevel enum
        appInsights['SeverityLevel'] = {
            Verbose : 0,
            Information : 1,
            Warning : 2,
            Error : 3,
            Critical : 4
        };
    
        // Collect global errors
        // Note: ApplicationInsightsAnalytics is the extension string identifier for
        //  AppAnalytics. It is defined in ApplicationInsights.ts:ApplicationInsights.identifer
        var analyticsCfg = ((aiConfig.extensionConfig || {}).ApplicationInsightsAnalytics ||{});
        if (!(aiConfig[strDisableExceptionTracking] === true || analyticsCfg[strDisableExceptionTracking] === true)) {
            var method = "onerror";
            _createMethods(["_" + method]);
            var originalOnError = win[method];
            win[method] = function(message, url, lineNumber, columnNumber, error) {
                var handled = originalOnError && originalOnError(message, url, lineNumber, columnNumber, error);
                if (handled !== true) {
                    appInsights["_" + method]({
                        message: message,
                        url: url,
                        lineNumber: lineNumber,
                        columnNumber: columnNumber,
                        error: error
                    });
                }
    
                return handled;
            };
            aiConfig.autoExceptionInstrumented = true;
        }
    
        return appInsights;
    })(snipConfig.cfg);

    // global instance must be set in this order to mitigate issues in ie8 and lower
    win[aiName] = aiSdk;
    
    function _onInit() {
        if (snipConfig.onInit) {
            snipConfig.onInit(aiSdk);
        }
    }

    // if somebody calls the snippet twice, don't report page view again
    if (aiSdk.queue && aiSdk.queue.length === 0) {
        aiSdk.queue.push(_onInit);
        aiSdk.trackPageView({});
    } else {
        // Already loaded so just call the onInit
        _onInit();
    }
})(window, document, {
    src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
    // name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
    // ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
    // useXhr: 1, // Use XHR instead of fetch to report failures (if available),
    // crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
    // onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
    cfg: { // Application Insights Configuration
        instrumentationKey:{{RLT - instrumentationKey}},
        disableAjaxTracking: true
    }
});
</script>

@MSNev
Copy link
Collaborator

MSNev commented Jan 25, 2021

Ok, so the issue is not that there is any ES6 only features (this code works in ES3), going over the links the issue appears to be that the google closure-compiler is miss reporting the failure (for apparent convenience of reporting) google/closure-compiler#3189.

Drilling into the details, the 3 functions that it's complaining about all fall into category 1 of the below and therefore don't have any unexpected side-effects on their usage. https://262.ecma-international.org/6.0/#sec-block-level-function-declarations-web-legacy-compatibility-semantics

The only solution that seems viable at this point in time would be to move these 3 functions outside of the if statement (originally included in the if for performance reasons, so they don't need to be created if the url is mis-configured.

As we are planning on some additional snippet changes later this year, I'm going to keep this open as a p3 (because there is no functional issues with the snippet) and however, get allocated to the snippet updates can include this minor change in a future version.

For yourself, (in the short term) as I'm thinking you probably want this resolved :-) would be to

  • grab a copy of this repo
  • Update the snippet to move the _handleError(), _handleLoad() and _createScript() functions before the if (targetSrc) (online 162 - https://github.com/microsoft/ApplicationInsights-JS/blob/master/AISKU/snippet/snippet.js#L162)
  • and then from the ~/AISKU/ folder run the following npm run build:snippet, this will update the snippet.min.js file in the ~/AISKU/snippet/ folder
  • And apart from the config settings on the end this is what we then publish -- so you can grab this and use it locally for your project.

;-)

@github-actions
Copy link

This Issue will be closed in 30 days. Please remove the "Stale" label or comment to avoid closure with no action.

@github-actions github-actions bot added the stale label Nov 22, 2021
@github-actions github-actions bot added the closed Automatically Closed Issue/PR label Dec 22, 2021
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Dec 23, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
closed Automatically Closed Issue/PR p3 snippet Snippet update required or suggested stale
Projects
None yet
Development

No branches or pull requests

2 participants