javascript decoding webpackJsonp to readable code - javascript

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

Related

Javascript Get Selected Text: Incorrect number of lines

I am using the following code
(function(e, t) {
"use strict";
var n = t.selection;
var i = t.getSelection;
var o = i || n;
var r = function(e) {
var t = Object.prototype.toString.call(e);
return typeof e === "object" && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(t) && e.hasOwnProperty("length") && (e.length === 0 || typeof e[0] === "object" && e[0].nodeType > 0)
};
var c = function(e, t) {
var n;
return function() {
var i = this,
o = arguments;
var r = function() {
n = null;
e.apply(i, o)
};
clearTimeout(n);
n = setTimeout(r, t)
}
};
var s = function(t, n) {
this.element = t;
this.callback = n || function() {};
this.isTouch = "ontouchstart" in e;
this.hasLib = e.jQuery && t instanceof e.jQuery || e.Zepto && t instanceof e.Zepto
};
s.prototype = {
events: function() {
var e = this.callback;
var t = this.getText;
this[this.isTouch ? "bindTouch" : "bindMouseUp"](function() {
e(t())
})
},
getText: function() {
var n = "";
if (i) {
n = e.getSelection().toString()
} else if (t.selection && t.selection.type !== "Control") {
n = t.selection.createRange().text
}
return n
},
checkForSelections: function(e, t, n) {
var i;
var o = function(e) {
var n = t();
var i = setInterval(function() {
if (t() !== n) {
e(t());
n = t()
} else if (t() === "") {
clearInterval(i)
}
}, 100)
};
var r = function() {
e.removeEventListener("touchend", c, false);
e.addEventListener("touchend", c, false);
if (i) {
clearInterval(i)
}
i = setInterval(function() {
var e = t();
if (e !== "") {
n(e);
c();
o(n)
}
}, 100)
};
var c = function() {
clearInterval(i);
e.removeEventListener("touchend", c, false)
};
e.addEventListener("touchstart", r, false)
},
bindTouch: function(e) {
var t = this.checkForSelections;
var n = this.getText;
if (this.hasLib) {
this.element.each(function() {
t(this, n, e)
});
return
}
var i = function(i) {
t(i, n, e)
};
if (!r(this.element)) {
i(this.element);
return
} [].forEach.call(this.element, function(e) {
i(e)
})
},
bindMouseUp: function(e) {
if (this.hasLib) {
this.element.on("mouseup", c(e, 150));
return
}
var t = function(t) {
t.addEventListener("mouseup", c(e, 150), false)
};
if (!r(this.element)) {
t(this.element);
return
} [].forEach.call(this.element, function(e) {
t(e)
})
}
};
e.selecting = function(e, t) {
if (!o) {
return
}
new s(e, t).events()
}
})(window, document);
And :
var myElement = document.body;
window.selecting(myElement, function(selector) {
var text = selector;
instance.publishState("text", text);
});
to basically get the selected/highlighted text by the user in the browser. I then use the selected text to work with it, make API calls etc.
Getting the selected text is fine, but unfortunately the number of lines in the returned text is usually incorrect which makes it impossible for me to work with.
Let me give you an example:
The user highlights the following text on the page:
Hello this is a test
Hello this is another test
The returned value from my code however than displays this text but with more line breaks in between. So for example I get returned:
Hello this is a test
Hello this is another test
This completely breaks my functionality, as I have to exactly know how many line breaks there actually are in order to work with the text. Any ideas what could be wrong or how I can access the browsers selected text with the correct number of line breaks?
The code
window.getSelection().toString()
will return the correct selection, which will produce in your case
Hello this is a test\n\nHello this is another test
Notice how you have two \n corresponding to the 2 newlines you have.
So if you do anything like this to display what the user has selected:
console.dir(window.getSelection().toString());
You will see correctly what the user has selected
Hello this is a test
Hello this is another test

How to use a rails condition within a .slim Javascript function?

In my .slim file I have a javascript block containing a URL, this URL needs to differ depending on which environment it is rendered in (staging / production etc). This is my first time using this format, so I'm not sure if what I'm trying to do is logically possible.
I aim to create a ternary operator which checks the Rails Env, if it is 'Production' do X, otherwise do Y.
Code below:
file.slim
javascript:
function zopimChat() {
window.zEmbed || function (e, t) {
var n, o, d, i, s, a = [],
r = document.createElement("iframe");
window.zESettings = {
webWidget: {
offset: {
vertical: "85px"
}
}
};
window.zEmbed = function () {
a.push(arguments)
}, window.zE = window.zE || window.zEmbed, r.src = "javascript:false", r.title = "", r.role = "presentation", (r.frameElement || r).style.cssText = "display: none", d = document.getElementsByTagName("script"), d = d[d.length - 1], d.parentNode.insertBefore(r, d), i = r.contentWindow, s = i.document;
try {
o = s
} catch (c) {
n = document.domain, r.src = 'javascript:var d=document.open();d.domain="' + n + '";void(0);', o = s
}
o.open()._l = function () {
var o = this.createElement("script");
n && (this.domain = n), o.id = "js-iframe-async", o.src = e, this.t = +new Date, this.zendeskHost = t, this.zEQueue = a, this.body.appendChild(o)
}, o.write('<body onload="document._l();">'), o.close()
}
# condition below
("https://assets.zendesk.com/embeddable_framework/main.js",
Rails.env.production? "testwebsite.zendesk.com" : "testwebsite-staging.zendesk.com" );
}
You can use interpolation:
javascript:
const railsEnv = "#{Rails.env}";
https://rdoc.info/gems/slim/frames#text-interpolation
In your case:
("https://assets.zendesk.com/embeddable_framework/main.js",
"#{Rails.env.production? ? "testwebsite.zendesk.com" : "testwebsite-staging.zendesk.com"}" );

Azure Application Insights not logging unhandled browser events or exceptions

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

Angular JS Best Practices for Organizing Dependencies and Variables

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);

What is the meaning of e.fn in this code

I am looking at this javascript code from the quojs library:
(function() {
var e;
e = function() {
var e, t, n;
t = [];
e = function(t, r) {
var i;
if (!t) {
return n()
} else if (e.toType(t) === "function") {
return e(document).ready(t)
} else {
i = e.getDOMObject(t, r);
return n(i, t)
}
};
n = function(e, r) {
e = e || t;
e.__proto__ = n.prototype;
e.selector = r || "";
return e
};
e.extend = function(e) {
Array.prototype.slice.call(arguments, 1).forEach(function(t) {
var n, r;
r = [];
for (n in t) {
r.push(e[n] = t[n])
}
return r
});
return e
};
n.prototype = e.fn = {};
return e
}();
which comes before this:
(function () {
(function (e) {
var t, n, r, i, u, a;
r = "parentNode";
t = /^\.([\w-]+)$/;
n = /^#[\w\d-]+$/;
i = /^[\w-]+$/;
e.query = function (e, r) {
var u;
r = r.trim();
if (t.test(r)) {
u = e.getElementsByClassName(r.replace(".", ""))
} else if (i.test(r)) {
u = e.getElementsByTagName(r)
} else if (n.test(r) && e === document) {
u = e.getElementById(r.replace("#", ""));
if (!u) {
u = []
}
} else {
u = e.querySelectorAll(r)
}
if (u.nodeType) {
return [u]
} else {
return Array.prototype.slice.call(u)
}
};
e.fn.find = function (t) {
I am trying to understand the meaning of e.fn.
I see that fn is not a reserved word. I think that e is just the name given to the event object passed as a parameter. So what is the meaning of e.fn? Is the code assuming that whatever is passed as e has a property called fn? Or is fn some kind of abbreviation that references the function?
Whatever is passed as e should have a property called fn. I would search the rest of the code for "fn" and see what you come up with.

Categories

Resources