Related
I'm attempting to log unhandled browser exceptions in an ASP.NET Core web application. I'm following the setup documentation noted here on learn.microsoft.com. I'm not currently seeing anything being logged, even if I manually call appInsights.trackException(ex). It should be noted that I am able to see logs that are coming from the backend code, just not anything from the client's browser.
While I can't post the code directly related to the project I'm working on, I've created a small web page that I can run locally just to recreate the issue.
<!DOCTYPE html>
<html lang="en">
<head>
<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: "myInstrumentationKey"
}
});
</script>
<script>
console.log(appInsights); // this produces an output, so appInsights is at least created
try {
x.hello; // x is not defined, this throws an exception
} catch (ex) {
appInsights.trackException(ex); // attempting to log exception manually
appInsights.flush();
throw ex; // attempting to log unhandled exception
}
</script>
</head>
</html>
In this code, I initialize everything using the snippet provided in the link above. I try to call x.hello, but x isn't defined so any exception is thrown. I then attempt to log that exception manually using appInsights.trackException(ex) and I also re-throw the exception because, according to the link above, unhandled browser exceptions should be logged automatically. I am however not seeing either of these events appear in application insights.
I know my instrumentation key is correct, because an incorrect one would yield some 400 errors when attempting to connect. This is what my network tab looks like after connecting.
Any ideas where I'm going wrong here?
I am following the same snippet which you are used.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<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: "Your Instrumentation key"
/* ...Other Configuration Options... */
}
});
</script>
<script>
//function getCookieValue(key) {
// const cookie = document.cookie
// .split('; ')
// .find(cookie => cookie.startsWith(key));
// return cookie ? cookie.split('=')[1] : null;
//}
//var telemetryInitializer = (envelope) => {
// const environment = getCookieValue('x-ms-routing-name') || 'production';
// envelope.data['slot'] = environment;
//}
//appInsights.addTelemetryInitializer(telemetryInitializer);
console.log(appInsights); // this produces an output, so appInsights is at least created
try {
s.hello; // x is not defined, this throws an exception
} catch (ex) {
//appInsights.trackException(ex); // attempting to log exception manually
appInsights.flush();
throw ex; // attempting to log unhandled exception
}
</script>
</head>
Without adding the appInsights.trackException(ex); I am able to see the uncaught ReferenceError in application insights.
Refer here for more info
there is a way to change this code into a clear and readable code ?
(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{"2wwy":function(n,t,e){n.exports=e("nhzr")},E8gZ:function(n,t,e){var o=e("jmDH"),i=e("w6GO"),r=e("NsO/"),u=e("NV0k").f;n.exports=function(n){return function(t){for(var e,c=r(t),a=i(c),f=a.length,s=0,l=[];f>s;)e=a[s++],o&&!u.call(c,e)||l.push(n?[e,c[e]]:c[e]);return l}}},f0Zw:function(n,t,e){"use strict";e.r(t);var o=e("q1tI"),i=e.n(o),r=e("/MKj"),u=e("2wwy"),c=e.n(u),a=e("G4qV"),f=Object(a.a)((function(n){return n.g_notifications}),(function(n){return c()(n)})),s=e("F7NL"),l=e("kOwS"),p=e("qNsG"),v=e("CnBM"),w=e.n(v)()({loader:function(){return Promise.all([e.e(0),e.e(6)]).then(e.bind(null,"OyQA"))},loading:function(){return null},modules:["Notification"]}),b=i.a.createElement,d=function(n){var t=n.notifications,e=n.onRemove;return b(i.a.Fragment,null,t.map((function(n){var t=n.id,o=Object(p.a)(n,["id"]);return b(w,Object(l.a)({onRemove:e},o,{key:t,id:t}))})))},O=i.a.createElement,m=Object(r.b)((function(n){return{notifications:f(n)}})),j=function(n){var t=n.dataset.id;Object(s.b)(t)},g=m((function(n){var t=n.notifications;return O(d,{onRemove:j,notifications:t})}));t.default=g},fW1p:function(n,t,e){var o=e("Y7ZC"),i=e("E8gZ")(!1);o(o.S,"Object",{values:function(n){return i(n)}})},nhzr:function(n,t,e){e("fW1p"),n.exports=e("WEpk").Object.values}}]);
This looks like output from Webpack 4.
If the site you're looking at exposes source maps, you will see a section under sources in your browser's dev tools labelled "Webpack", which will contain the source for the scripts bundled using Webpack.
If the site doesn't expose source maps, the first step is to format the code. You can then start manually renaming variables as you figure out what they do. In this case, there must be more scripts on the site because there seem to be references to modules not defined in the file.
Passing this code through Prettier gives:
(window.webpackJsonp = window.webpackJsonp || []).push([
[7],
{
"2wwy": function(n, t, e) {
n.exports = e("nhzr");
},
E8gZ: function(n, t, e) {
var o = e("jmDH"),
i = e("w6GO"),
r = e("NsO/"),
u = e("NV0k").f;
n.exports = function(n) {
return function(t) {
for (var e, c = r(t), a = i(c), f = a.length, s = 0, l = []; f > s; )
(e = a[s++]), (o && !u.call(c, e)) || l.push(n ? [e, c[e]] : c[e]);
return l;
};
};
},
f0Zw: function(n, t, e) {
"use strict";
e.r(t);
var o = e("q1tI"),
i = e.n(o),
r = e("/MKj"),
u = e("2wwy"),
c = e.n(u),
a = e("G4qV"),
f = Object(a.a)(
function(n) {
return n.g_notifications;
},
function(n) {
return c()(n);
}
),
s = e("F7NL"),
l = e("kOwS"),
p = e("qNsG"),
v = e("CnBM"),
w = e.n(v)()({
loader: function() {
return Promise.all([e.e(0), e.e(6)]).then(e.bind(null, "OyQA"));
},
loading: function() {
return null;
},
modules: ["Notification"]
}),
b = i.a.createElement,
d = function(n) {
var t = n.notifications,
e = n.onRemove;
return b(
i.a.Fragment,
null,
t.map(function(n) {
var t = n.id,
o = Object(p.a)(n, ["id"]);
return b(w, Object(l.a)({ onRemove: e }, o, { key: t, id: t }));
})
);
},
O = i.a.createElement,
m = Object(r.b)(function(n) {
return { notifications: f(n) };
}),
j = function(n) {
var t = n.dataset.id;
Object(s.b)(t);
},
g = m(function(n) {
var t = n.notifications;
return O(d, { onRemove: j, notifications: t });
});
t.default = g;
},
fW1p: function(n, t, e) {
var o = e("Y7ZC"),
i = e("E8gZ")(!1);
o(o.S, "Object", {
values: function(n) {
return i(n);
}
});
},
nhzr: function(n, t, e) {
e("fW1p"), (n.exports = e("WEpk").Object.values);
}
}
]);
finding yourself in this is almost impossible, I mean that the result of decoding was on this principle:
var func = {
init: function() {
console.log('test');
this.set();
},
set: function(){
$('.body .test').innerHTML = 'test';
}
}
func.init();
easy and legible
I am working on a project where I am making sense of what a bunch of overseas developers did in Angular JS a year before I joined the company. It's a huge project with no documentation. I was curious about if anyone has seen anything like this with so many dependencies included in the code and then each dependency renamed as a variable like (e,t,n,r,s,a), which is then included in a complex nested structure that's 140 lines long for one controller. Is this considered best practices for coding?
I have a feeling it's messier than it needs to be. Does anyone know an effective tool or methodology way to map dependencies, variables, etc. and re-organize Angular JS code?
Sample Code
define(["./../_module", "moment"], function (e, t) {
"use strict";
e.controller("trendController", ["$scope", "$state", "$q", "$rootScope", "labelsService", "trendService", "gridSettingsService", "colorpickerSettingsService", "loadDisplay", "uiGridConstants", "APP_CONSTANTS", "globalErrorService", "utilsService", "usersService", "browserHelper", "pageErrorHandlingHelper", function (e, t, n, r, s, a, l, d, i, o, c, u, g, f, b, v) {
function h(t) {
var n = angular.copy(C);
return n.graphColor = e.defaultColors[t], n
}
function D() {
var t = n.all([O, j])["catch"](p.errorHandlingActions.loadedFailed);
i.addDisplay(t, "", e.gridAreaId)
}
var p = this;
p.errorHandlingActions = v.errorHandlingActions, e.hasMeasurementsUnitsClash = !1, e.gridAreaId = "trendWrapper", e.labels = {
genchoosedev: "",
genchooseobj: "",
generror: "",
gennodata: "",
genhour: "",
genday: "",
genweek: "",
gencustom: "",
gendatetime: "",
tndlink: "",
tnddevlbl: "",
tndptlbl: "",
tndclrlbl: "",
tndexport: "",
tndtbllbl: "",
tndgphlbl: "",
tnddataempty: "",
tndtime: "",
tndpointhdr: "",
tndgphmeas: ""
};
var O = s.getLabelsForPage(e.labels).then(function (t) {
e.labels = t
});
e.defaultColors = c.TRENDS.DEFAULT_COLORS, e.trendPointsMax = c.TRENDS.TREND_POINTS_MAX, e.devicesObjects = [], e.defaultColorPickerOptions = d.getSettings(), e.isPredefinedFiltersUsed = !1;
var j = a.getAllTrendDeviceObjects().then(function (t) {
return _.forEach(t, function (e) {
e.objects = _.sortBy(e.objects, "objName")
}), e.devicesObjects = _.sortBy(t, "name"), f.getTrendInfoSettings(r.sessionUser.userName).then(function (t) {
if (t.trendLines && "0" != t.trendLines[0].devInst) {
e.startDate = t.trendStart, e.endDate = t.trendEnd;
var n = [];
_.forEach(t.trendLines, function (t) {
var r = angular.copy(C);
r.deviceObjects = _.find(e.devicesObjects, {
id: t.devInst
}), r.selectedObject = _.find(r.deviceObjects.objects, {
objID: t.objID
}), r.graphColor = t.colorVal, n.push(r)
}), e.selectedDeviceObjects = n, e.isPredefinedFiltersUsed = !0, e.triggerReloadDataWithPredefinedFilters()
}
e.$watch("selectedDeviceObjects", function (t, n) {
var r = _.last(t);
if (angular.isDefined(r) && null !== r.selectedObject) {
var s = parseInt(r.selectedObject.objID);
!isNaN(s) && angular.isNumber(s) && t.length < e.trendPointsMax && t.push(h(t.length))
}
if (t.length >= 2) {
var a = t[t.length - 2];
null === a.selectedObject && null === r.deviceObjects && t.splice(t.length - 1, 1)
}
e.HasDataToDisplay = _.filter(t, function (e) {
return null !== e.selectedObject
}).length > 0, e.saveTrendInfoForCurrentUser()
}, !0), e.$watchGroup(["startDate", "endDate"], function (t, n) {
e.saveTrendInfoForCurrentUser()
})
})
}),
C = {
deviceObjects: null,
selectedObject: null,
gridOptions: null,
graphColor: e.defaultColors[0]
};
e.selectedDeviceObjects = [angular.copy(C)], e.HasDataToDisplay = !1, D(), e.reloadHandler = null, e.unitsOfMeasureCounts = [], e.$watchCollection("unitsOfMeasureCounts", function (t) {
var n = {};
_.each(t, function (e) {
null !== e && (n[e] ? n[e]++ : n[e] = 1)
}), e.hasMeasurementsUnitsClash = Object.keys(n).length > 2
}), e.TriggerDataLoad = function (t, n) {
null === n.deviceObjects && (n.selectedObject = null), n.selectedObject ? e.unitsOfMeasureCounts[t] = n.selectedObject.units : e.unitsOfMeasureCounts[t] = null, null != e.reloadHandler && e.reloadHandler(t, n)
}, e.colorChangedHandler = null, e.TriggerColorChanged = function (t, n) {
null !== e.colorChangedHandler && e.colorChangedHandler(t, n)
};
var S = function () {
var t = {
preselectedDataPoints: [],
datesRange: {
start: e.startDate,
end: e.endDate
}
};
return _.forEach(e.selectedDeviceObjects, function (e) {
angular.isDefined(e.deviceObjects) && null != e.deviceObjects && angular.isDefined(e.selectedObject) && null != e.selectedObject && t.preselectedDataPoints.push({
deviceId: e.deviceObjects.id,
objectId: e.selectedObject.objID
})
}), t
};
e.redirectToExportTrend = function () {
var e = S(),
n = JSON.stringify(e);
t.go("exportTrendData", {
paramsJson: n
})
}, e.saveTrendInfoForCurrentUser = function () {
var t = {
selectedDeviceTrends: e.selectedDeviceObjects,
datesRange: {
start: e.startDate,
end: e.endDate
}
};
return f.updateTrendInfoSettings(r.sessionUser.userName, t).then(function (e) {}, p.errorHandlingActions.failed)
}, e.startDate = null, e.endDate = null, e.exportSelectedPoints = function () {
var e = S();
return a.exportTrendData(e.preselectedDataPoints, e.datesRange).then(function (e) {
angular.isDefined(e) && e.length > 0 && b.saveFileAsCSV(e)
}, p.errorHandlingActions.failed)
}
}])
});
I highly doubt this is the original code, probably it's the output of some minification / obfuscator tool.
the single letter variable is an optimization applied by minifiers in order to reduce the size of the project, but they actually remove spaces, comments, new line etc..
Here my guess is that their aim was to obfuscate the code, and this is undoable. you cannot go back to the original names. Online you can find some JS beautifier but they just format the code to make it "better looking" if it isn't, but this code is already formatted so doesn't help.
the only way to retrieve the original variables names would be to have some sort of mapping (actualName / oldName) saved somewhere.
personally i would get in touch with these guys to understand if there's any trace of the original code.
The use of variables like (e,t,n,r,s,a) is not a best practices, because they are meaningless, this is an example of how I manage the dependency inyection in the controller, I have created a function notifyCtrl, the parameters of the function are my dependencies, then I send the function declaration as parameter in my angular.module.controller
function notifyCtrl($scope, notify) {
$scope.msg = 'Hello! This is a sample message!';
$scope.demo = function () {
notify({
message: $scope.msg,
classes: $scope.classes,
templateUrl: $scope.template
});
};
$scope.closeAll = function () {
notify.closeAll();
};
}
angular
.module('angularModule')
.controller('notifyCtrl', notifyCtrl);
I would like to know what kind of safety measurements do you take into consideration when importing javascript code from another author (stated free to use) into your project.
So if you came across a super simple navigation template from codepen, after I d/l it I found out it didn't work unless it uses a js file that contained an XMLHttpRequest (why would you need an http request for this template, I don't know) here's another example with a lot of var declarations and replaces.
So to reiterate my question, other than seeing if this following code is dodgy, I would also like to know why would you need an http request for a simple website like this and what measurement would you take when you use other people's code, or maybe you never use other people code?
!function () {
function e(e, r) {
return [].slice.call((r || document).querySelectorAll(e))
}
if (window.addEventListener) {
var r = window.StyleFix = {
link: function (e) {
try {
if ("stylesheet" !== e.rel || e.hasAttribute("data-noprefix"))return
} catch (t) {
return
}
var n, i = e.href || e.getAttribute("data-href"),
a = i.replace(/[^\/]+$/, ""), o = (/^[a-z]{3,10}:/.exec(a) || [""])[0],
s = (/^[a-z]{3,10}:\/\/[^\/]+/.exec(a) || [""])[0], l = /^([^?]*)\??/.exec(i)[1], u = e.parentNode, p = new XMLHttpRequest;
p.onreadystatechange = function () {
4 === p.readyState && n()
}, n = function () {
var t = p.responseText;
if (t && e.parentNode && (!p.status || p.status < 400 || p.status > 600)) {
if (t = r.fix(t, !0, e), a) {
t = t.replace(/url\(\s*?((?:"|')?)(.+?)\1\s*?\)/gi, function (e, r, t) {
return /^([a-z]{3,10}:|#)/i.test(t) ? e : /^\/\//.test(t) ? 'url("' + o + t + '")' : /^\//.test(t) ? 'url("' + s + t + '")' : /^\?/.test(t) ? 'url("' + l + t + '")' : 'url("' + a + t + '")'
});
var n = a.replace(/([\\\^\$*+[\]?{}.=!:(|)])/g, "\\$1");
t = t.replace(RegExp("\\b(behavior:\\s*?url\\('?\"?)" + n, "gi"), "$1")
}
var i = document.createElement("style");
i.textContent = t, i.media = e.media, i.disabled = e.disabled, i.setAttribute("data-href", e.getAttribute("href")), u.insertBefore(i, e), u.removeChild(e), i.media = e.media
}
};
try {
p.open("GET", i), p.send(null)
} catch (t) {
"undefined" != typeof XDomainRequest && (p = new XDomainRequest, p.onerror = p.onprogress = function () {
}, p.onload = n, p.open("GET", i), p.send(null))
}
e.setAttribute("data-inprogress", "")
}, styleElement: function (e) {
if (!e.hasAttribute("data-noprefix")) {
var t = e.disabled;
e.textContent = r.fix(e.textContent, !0, e), e.disabled = t
}
}, styleAttribute: function (e) {
var t = e.getAttribute("style");
t = r.fix(t, !1, e), e.setAttribute("style", t)
}, process: function () {
e("style").forEach(StyleFix.styleElement), e("[style]").forEach(StyleFix.styleAttribute)
}, register: function (e, t) {
(r.fixers = r.fixers || []).splice(void 0 === t ? r.fixers.length : t, 0, e)
}, fix: function (e, t, n) {
for (var i = 0; i < r.fixers.length; i++)e = r.fixers[i](e, t, n) || e;
return e
}, camelCase: function (e) {
return e.replace(/-([a-z])/g, function (e, r) {
return r.toUpperCase()
}).replace("-", "")
}, deCamelCase: function (e) {
return e.replace(/[A-Z]/g, function (e) {
return "-" + e.toLowerCase()
})
}
};
!function () {
setTimeout(function () {
}, 10), document.addEventListener("DOMContentLoaded", StyleFix.process, !1)
}()
}
}(), function (e) {
function r(e, r, n, i, a) {
if (e = t[e], e.length) {
var o = RegExp(r + "(" + e.join("|") + ")" + n, "gi");
a = a.replace(o, i)
}
return a
}
if (window.StyleFix && window.getComputedStyle) {
var t = window.PrefixFree = {
prefixCSS: function (e, n) {
var i = t.prefix;
if (t.functions.indexOf("linear-gradient") > -1 && (e = e.replace(/(\s|:|,)(repeating-)?linear-gradient\(\s*(-?\d*\.?\d*)deg/gi, function (e, r, t, n) {
return r + (t || "") + "linear-gradient(" + (90 - n) + "deg"
})), e = r("functions", "(\\s|:|,)", "\\s*\\(", "$1" + i + "$2(", e), e = r("keywords", "(\\s|:)", "(\\s|;|\\}|$)", "$1" + i + "$2$3", e), e = r("properties", "(^|\\{|\\s|;)", "\\s*:", "$1" + i + "$2:", e), t.properties.length) {
var a = RegExp("\\b(" + t.properties.join("|") + ")(?!:)", "gi");
e = r("valueProperties", "\\b", ":(.+?);", function (e) {
return e.replace(a, i + "$1")
}, e)
}
return n && (e = r("selectors", "", "\\b", t.prefixSelector, e), e = r("atrules", "#", "\\b", "#" + i + "$1", e)), e = e.replace(RegExp("-" + i, "g"), "-"), e = e.replace(/-\*-(?=[a-z]+)/gi, t.prefix)
}, property: function (e) {
return (t.properties.indexOf(e) ? t.prefix : "") + e
}, value: function (e) {
return e = r("functions", "(^|\\s|,)", "\\s*\\(", "$1" + t.prefix + "$2(", e), e = r("keywords", "(^|\\s)", "(\\s|$)", "$1" + t.prefix + "$2$3", e)
}, prefixSelector: function (e) {
return e.replace(/^:{1,2}/, function (e) {
return e + t.prefix
})
}, prefixProperty: function (e, r) {
var n = t.prefix + e;
return r ? StyleFix.camelCase(n) : n
}
};
!function () {
var e = {}, r = [], n = getComputedStyle(document.documentElement, null), i = document.createElement("div").style, a = function (t) {
if ("-" === t.charAt(0)) {
r.push(t);
var n = t.split("-"), i = n[1];
for (e[i] = ++e[i] || 1; n.length > 3;) {
n.pop();
var a = n.join("-");
o(a) && -1 === r.indexOf(a) && r.push(a)
}
}
}, o = function (e) {
return StyleFix.camelCase(e) in i
};
if (n.length > 0)for (var s = 0; s < n.length; s++)a(n[s]); else for (var l in n)a(StyleFix.deCamelCase(l));
var u = {uses: 0};
for (var p in e) {
var f = e[p];
u.uses < f && (u = {prefix: p, uses: f})
}
t.prefix = "-" + u.prefix + "-", t.Prefix = StyleFix.camelCase(t.prefix), t.properties = [];
for (var s = 0; s < r.length; s++) {
var l = r[s];
if (0 === l.indexOf(t.prefix)) {
var c = l.slice(t.prefix.length);
o(c) || t.properties.push(c)
}
}
"Ms" != t.Prefix || "transform" in i || "MsTransform" in i || !("msTransform" in i) || t.properties.push("transform", "transform-origin"), t.properties.sort()
}(), function () {
function e(e, r) {
return i[r] = "", i[r] = e, !!i[r]
}
var r = {
"linear-gradient": {property: "backgroundImage", params: "red, teal"},
calc: {property: "width", params: "1px + 5%"},
element: {property: "backgroundImage", params: "#foo"},
"cross-fade": {property: "backgroundImage", params: "url(a.png), url(b.png), 50%"}
};
r["repeating-linear-gradient"] = r["repeating-radial-gradient"] = r["radial-gradient"] = r["linear-gradient"];
var n = {
initial: "color",
"zoom-in": "cursor",
"zoom-out": "cursor",
box: "display",
flexbox: "display",
"inline-flexbox": "display",
flex: "display",
"inline-flex": "display",
grid: "display",
"inline-grid": "display",
"min-content": "width"
};
t.functions = [], t.keywords = [];
var i = document.createElement("div").style;
for (var a in r) {
var o = r[a], s = o.property, l = a + "(" + o.params + ")";
!e(l, s) && e(t.prefix + l, s) && t.functions.push(a)
}
for (var u in n) {
var s = n[u];
!e(u, s) && e(t.prefix + u, s) && t.keywords.push(u)
}
}(), function () {
function r(e) {
return a.textContent = e + "{}", !!a.sheet.cssRules.length
}
var n = {
":read-only": null,
":read-write": null,
":any-link": null,
"::selection": null
}, i = {keyframes: "name", viewport: null, document: 'regexp(".")'};
t.selectors = [], t.atrules = [];
var a = e.appendChild(document.createElement("style"));
for (var o in n) {
var s = o + (n[o] ? "(" + n[o] + ")" : "");
!r(s) && r(t.prefixSelector(s)) && t.selectors.push(o)
}
for (var l in i) {
var s = l + " " + (i[l] || "");
!r("#" + s) && r("#" + t.prefix + s) && t.atrules.push(l)
}
e.removeChild(a)
}(), t.valueProperties = ["transition", "transition-property"], e.className += " " + t.prefix, StyleFix.register(t.prefixCSS)
}
}(document.documentElement);
Here is the code.
why would you need an http request for a simple website like this
You don't. The effect on the page is done entirely with CSS. You can delete all the JS and it still works.
The JavaScript is a minified (which is why it's so hard to read) version of this library, which is a complicated and brittle attempt to adapt CSS styles for older browsers that require browser-specific property prefixes for some of the newer CSS features. It has to do XMLHttpRequests in order to fetch the stylesheet files and fiddle with them.
It's unclear why the example code has bothered use that library, since the CSS already contains the prefixed versions of the properties. But that's the joy and curse of grabbing random code off the internet, you have no idea if it's at all sensible...
I would like to know what kind of safety measurements do you take into consideration when importing javascript code from another author (stated free to use) into your project.
There's no magic bullet. You have to read and understand what all the code is doing, or you have to completely trust the author of the code (and the operators of the service hosting it, if you're linking it directly from a third-party server like a CDN).
I am trying to modify MicrosoftAjaxWebForms.js file which is default ajax file of asp.net 4.5 and ASP.NET AJAX Control Toolkit version is 16.1.0.0
Here an example project to test out : https://github.com/FurkanGozukara/tempSite/
Open project and go to trialpage.aspx and click that button. You will see the error
Here the full MicrosoftAjaxWebForms.js : http://pastebin.com/pU3rBLKW
It also uses functions from MicrosoftAjax.js if you need that : http://pastebin.com/CPCm9BZy
What I want is, delaying the event _onFormSubmitCompleted
I have tried like below but it doesn't work.
MicrosoftAjaxWebForms.js:914 Uncaught TypeError: this._tempCompleted is not a function
It gives the error above
_onFormSubmitCompleted: function (c) {
console.log("_onFormSubmitCompleted");
setTimeout(function () {
this._tempCompleted(c);
}, 1111);
}, _tempCompleted: function (c) {
console.log("testcompleted");
this._processingRequest = true;
if (c.get_timedOut()) {
this._endPostBack(this._createPageRequestManagerTimeoutError(), c, null);
return
}
if (c.get_aborted()) {
this._endPostBack(null, c, null);
return
}
if (!this._request || c.get_webRequest() !== this._request) return;
if (c.get_statusCode() !== 200) {
this._endPostBack(this._createPageRequestManagerServerError(c.get_statusCode()), c, null);
return
}
var a = this._parseDelta(c);
if (!a) return;
var b, e;
if (a.asyncPostBackControlIDsNode && a.postBackControlIDsNode && a.updatePanelIDsNode && a.panelsToRefreshNode && a.childUpdatePanelIDsNode) {
var r = this._updatePanelIDs,
n = this._updatePanelClientIDs,
i = a.childUpdatePanelIDsNode.content,
p = i.length ? i.split(",") : [],
m = this._splitNodeIntoArray(a.asyncPostBackControlIDsNode),
o = this._splitNodeIntoArray(a.postBackControlIDsNode),
q = this._splitNodeIntoArray(a.updatePanelIDsNode),
g = this._splitNodeIntoArray(a.panelsToRefreshNode),
h = a.version4;
for (b = 0, e = g.length; b < e; b += h ? 2 : 1) {
var j = (h ? g[b + 1] : "") || this._uniqueIDToClientID(g[b]);
if (!document.getElementById(j)) {
this._endPostBack(Error.invalidOperation(String.format(Sys.WebForms.Res.PRM_MissingPanel, j)), c, a);
return
}
}
var f = this._processUpdatePanelArrays(q, m, o, h);
f.oldUpdatePanelIDs = r;
f.oldUpdatePanelClientIDs = n;
f.childUpdatePanelIDs = p;
f.panelsToRefreshIDs = g;
a.updatePanelData = f
}
a.dataItems = {};
var d;
for (b = 0, e = a.dataItemNodes.length; b < e; b++) {
d = a.dataItemNodes[b];
a.dataItems[d.id] = d.content
}
for (b = 0, e = a.dataItemJsonNodes.length; b < e; b++) {
d = a.dataItemJsonNodes[b];
a.dataItems[d.id] = Sys.Serialization.JavaScriptSerializer.deserialize(d.content)
}
var l = this._get_eventHandlerList().getHandler("pageLoading");
if (l) l(this, this._getPageLoadingEventArgs(a));
Sys._ScriptLoader.readLoadedScripts();
Sys.Application.beginCreateComponents();
var k = Sys._ScriptLoader.getInstance();
this._queueScripts(k, a.scriptBlockNodes, true, false);
this._processingRequest = true;
k.loadScripts(0, Function.createDelegate(this, Function.createCallback(this._scriptIncludesLoadComplete, a)), Function.createDelegate(this, Function.createCallback(this._scriptIncludesLoadFailed, a)), null)
},
How should i modify the entire javascript or that function to add a custom delay feature?
So i can delay the client update at the client side as i wish after the postback is completed
Here my bounty having related question : How to defer the update at the client side after async postback in updatepanel