override javascript function local variable - javascript

There is an external function GoSearch which is exist in a javascript file search.js
How to override the private/local variable (b) of GoSearch function.
Example modify the variable b="?" to b="?cs=This Site&u=http://google.com"
GoSearch(q, G, p, E, r, F, D, C, B, j, n, z, y, x, w, A, l, v) {
ULShpi: ;
try {
AddSearchoptionsToQuery()
} catch (H) {}
var i = document.forms[0].elements[G].value;
i = i.replace(/\s*$/, "");
var u = "1";
if (q) u = document.forms[0].elements[q].Value;
if (i == "" || u == "0") {
alert(v);
if (null != event) {
event.returnValue = false;
return false
} else return
}
var b = "?";
if (suggestedQuery) b += "sq=1&";
b += "k=" + encodeURIComponent(i);
for (var k = ["rm", "rm1", "rm2", "rm3", "rm4", "rm5", "ql", "ql1", "ql2", "ql3", "ql4", "ql5", "v", "v1", "v2", "v3", "v4", "v5", "hs", "hs1", "hs2", "hs3", "hs4", "hs5"], h = 0; h < k.length; h++) {
var m = GetUrlKeyValue(k[h], true);
if (m && m.length > 0) b += "&" + k[h] + "=" + m
}
if (l != null && l != "") b += "&r=" + encodeURIComponent(l);
if (null != p) {
var t = document.forms[0].elements[p].value;
if (E) b += canonicalizedUtf8FromUnicode(" " + t);
else b += "&a=" + canonicalizedUtf8FromUnicode(" " + t)
}
var a = null,
c = "",
d = "",
o = null != j;
if (o) {
c = j;
d = j
} else if (r) {
a = document.forms[0].elements[F];
c = a.options[a.selectedIndex].getAttribute("scope");
d = a.options[a.selectedIndex].value
}
if (r || o) {
var f = "",
g = "",
e = false;
if (d == z) {
f = d;
c = "";
g = document.forms[0].elements[D].value;
e = true
}
if (d == y) {
f = d;
c = "";
g = document.forms[0].elements[C].value;
e = true
}
if (d == x) {
f = c;
c = "";
g = document.forms[0].elements[B].value;
e = true
}
if (c == w) {
c = a.options[a.selectedIndex].value;
e = true
}
if (e) n = A;
if (c != "") {
b += "&s=" + encodeURIComponent(c);
if (a.options[a.selectedIndex].value != "" && !e) n = a.options[a.selectedIndex].value
}
if (f != "") b += "&cs=" + encodeURIComponent(f);
if (g != "") b += "&u=" + encodeURIComponent(g)
}
var I = document.forms[0];
try {
external.AutoCompleteSaveForm(I)
} catch (s) {}
window.location = n + b;
try {
if (null != event) event.returnValue = false
} catch (s) {}
return
}

You can replace the GoSearch function with your own just on the page with the Search Box - by a delegate control.
Create a user control (ASCX) that puts JavaScript code on the page with the modified GoSearch function. Create a SP solution with a feature that will place the control to AdditionalPageHead - to every page head on the site or site collection where you activate the feature.
Check out how the search.js gets loaded on your page. If it is done not directly in the page head but delayed, you'd have to perform the GoSearch replacement dynamically after the search.js is loaded:
function ReplaceGoSearch {
GoSearch = function(...) {
...
};
}
ExecuteOrDelayUntilScriptLoaded(ReplaceGoSearch, "search.js");
--- Ferda

The fastest way that you can do this, is don't link to the external file directly. Download your version of the file, change what you need, and then serve that to your pages.
You can even go so far to download the file on the fly to your server, modify it, and push it out to the requesting page.

Related

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

How to cancel or abort image download in Three.js TextureLoader

I have an image gallery project where the user can move around the 3D space and the images start downloading as he gets near them. Since he can be moving around all the time, getting away from those images which already started downloading, I'd need to cancel these downloads (they no longer need to download as they are not to be seen anymore).
I download them with Three.TextureLoader and was hoping to find some method to stop/cancel/abort the download, but looks like it doesn't exist. I found these threads related to the topic:
https://github.com/mrdoob/three.js/pull/6649
https://github.com/mrdoob/three.js/issues/6641
But I didn't find where to add the suggested "return request" in the Three code in my version of Three. I think this is the section where it should be found, but I don't quite get exactly where should I add such return statement:
Object.assign(Ja.prototype, {
load: function(a, b, c, d) {
void 0 === a && (a = "");
void 0 !== this.path && (a = this.path + a);
a = this.manager.resolveURL(a);
var e = this
, f = jd.get(a);
if (void 0 !== f)
return e.manager.itemStart(a),
setTimeout(function() {
b && b(f);
e.manager.itemEnd(a)
}, 0),
f;
if (void 0 !== Ta[a])
Ta[a].push({
onLoad: b,
onProgress: c,
onError: d
});
else {
var g = a.match(/^data:(.*?)(;base64)?,(.*)$/);
if (g) {
c = g[1];
var h = !!g[2]
, g = g[3]
, g = window.decodeURIComponent(g);
h && (g = window.atob(g));
try {
var k = (this.responseType || "").toLowerCase();
switch (k) {
case "arraybuffer":
case "blob":
for (var l = new Uint8Array(g.length), h = 0; h < g.length; h++)
l[h] = g.charCodeAt(h);
var m = "blob" === k ? new Blob([l.buffer],{
type: c
}) : l.buffer;
break;
case "document":
m = (new DOMParser).parseFromString(g, c);
break;
case "json":
m = JSON.parse(g);
break;
default:
m = g
}
window.setTimeout(function() {
b && b(m);
e.manager.itemEnd(a)
}, 0)
} catch (t) {
window.setTimeout(function() {
d && d(t);
e.manager.itemEnd(a);
e.manager.itemError(a)
}, 0)
}
} else {
Ta[a] = [];
Ta[a].push({
onLoad: b,
onProgress: c,
onError: d
});
var n = new XMLHttpRequest;
n.open("GET", a, !0);
n.addEventListener("load", function(b) {
var c = b.target.response;
jd.add(a, c);
var d = Ta[a];
delete Ta[a];
if (200 === this.status) {
for (var f = 0, g = d.length; f < g; f++) {
var h = d[f];
if (h.onLoad)
h.onLoad(c)
}
e.manager.itemEnd(a)
} else if (0 === this.status) {
console.warn("THREE.FileLoader: HTTP Status 0 received.");
f = 0;
for (g = d.length; f < g; f++)
if (h = d[f],
h.onLoad)
h.onLoad(c);
e.manager.itemEnd(a)
} else {
f = 0;
for (g = d.length; f < g; f++)
if (h = d[f],
h.onError)
h.onError(b);
e.manager.itemEnd(a);
e.manager.itemError(a)
}
}, !1);
n.addEventListener("progress", function(b) {
for (var c = Ta[a], d = 0, e = c.length; d < e; d++) {
var f = c[d];
if (f.onProgress)
f.onProgress(b)
}
}, !1);
n.addEventListener("error", function(b) {
var c = Ta[a];
delete Ta[a];
for (var d = 0, f = c.length; d < f; d++) {
var g = c[d];
if (g.onError)
g.onError(b)
}
e.manager.itemEnd(a);
e.manager.itemError(a)
}, !1);
void 0 !== this.responseType && (n.responseType = this.responseType);
void 0 !== this.withCredentials && (n.withCredentials = this.withCredentials);
n.overrideMimeType && n.overrideMimeType(void 0 !== this.mimeType ? this.mimeType : "text/plain");
for (h in this.requestHeader)
n.setRequestHeader(h, this.requestHeader[h]);
n.send(null)
}
e.manager.itemStart(a);
return n
}
return n
},
setPath: function(a) {
this.path = a;
return this
},
setResponseType: function(a) {
this.responseType = a;
return this
},
setWithCredentials: function(a) {
this.withCredentials = a;
return this
},
setMimeType: function(a) {
this.mimeType = a;
return this
},
setRequestHeader: function(a) {
this.requestHeader = a;
return this
}
});
Can anybody point me in the right direction? Or perhaps another solution such as loading the image in another way (jQuery, perhaps?) and then pass the texture to my material somehow? This is my current callback for TextureLaoder:
obj.handleTexture = function (size, texture) {
obj.mesh.material.map = texture;
obj.mesh.material.needsUpdate = true;
};
Many thanks
If you need to abort the image loader, check out the source code: https://github.com/mrdoob/three.js/blob/dev/src/loaders/ImageLoader.js
The new ImageLoader().load(...) function returns an XHTML image element (<img />). But this element is not accessible externally. Therefore you can easily write your own function to load textures, and override the existing one.
The function below is mostly copied from: https://github.com/mrdoob/three.js/blob/dev/src/loaders/TextureLoader.js Make sure that in the latest version of ThreeJS, you check if the source code below is the same (except for the additional abort function).
THREE.TextureLoader.prototype.load = function(url, onLoad, onProgress, onError)
{
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader(this.manager);
loader.setCrossOrigin(this.crossOrigin);
loader.setPath(this.path);
var image = loader.load(url, function(image)
{
texture.image = image;
// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat;
texture.needsUpdate = true;
if(onLoad !== undefined)
{
onLoad( texture );
}
}, onProgress, onError);
// add this function to the texture
texture.abort = function()
{
if(image && typeof image.hasAttribute === 'function')
{
image.src = '';
}
};
return texture;
};
Usage:
var texLoader = new THREE.TextureLoader();
var texRequest = texLoader.load('https://example.com/image.jpg', function(texture)
{
clearTimeout(texTimer);
// use loaded texture
...
});
// For example, abort after 200ms if still loading:
var texTimer = setTimeout(function()
{
texRequest.abort();
}, 200);

What is nio.js?

I am seeing an unknown script being displayed on all pages hosted on my site. This was not added by me to any of the pages, so i am assuming the hosting company is adding it on the fly when a page is requested.
This is what is added to the the page
<script>
! function(n, e, i, o, t) {
'use strict';
if (!n.nio) {
n.nio = function() {
n.nio.execAction ? n.nio.execAction.apply(window.nio, arguments) : n.nio.queue.push(arguments)
}, n.nio.push = n.nio, n.nio.loaded = !0, n.nio.version = '1.0', n.nio.queue = [];
var s = e.createElement(i);
s.async = !0, s.src = o;
var r = e.getElementsByTagName(i)[0];
r.parentNode.insertBefore(s, r)
}
}(window, document, 'script', '//cdn.narrative.io/js/nio-js/v1.1/nio.js');
nio('init', 9);
</script>
<noscript><img height='1' width='1' style='display:none' src='https://io.narrative.io?noscript=1&id=9'/></noscript>
This is what the nio.js file contains.
! function(t, e, n, r, i) {
"use strict";
var o, a, u = "__nio";
if (!t.nio || 1 !== t.nio.libLoaded) {
var s = function() {
return "//" + r
},
c = function(t) {
var e = typeof t;
return "object" === e && "function" !== e && null !== t
};
o = "undefined" != typeof JSON && null !== JSON && JSON.stringify ? JSON.stringify : function() {
var t = Object.prototype.toString,
e = Array.isArray || function(e) {
return "[object Array]" === t.call(e)
},
n = {
'"': '\\"',
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t"
},
r = function(t) {
return n[t] || "\\u" + (t.charCodeAt(0) + 65536).toString(16).substr(1)
},
i = /[\\"\u0000-\u001F\u2028\u2029]/g;
return function o(n) {
if (null == n) return "null";
if ("number" == typeof n) return isFinite(n) ? n.toString() : "null";
if ("boolean" == typeof n) return n.toString();
if ("object" == typeof n) {
if ("function" == typeof n.toJSON) return o(n.toJSON());
if (e(n)) {
for (var a = "[", u = 0; u < n.length; u++) a += (u ? ", " : "") + o(n[u]);
return a + "]"
}
if ("[object Object]" === t.call(n)) {
var s = [];
for (var c in n) n.hasOwnProperty(c) && s.push(o(c) + ": " + o(n[c]));
return "{" + s.join(", ") + "}"
}
}
return '"' + n.toString().replace(i, r) + '"'
}
}();
var f = Object.assign || function(t) {
if (t === i || null === t) throw new TypeError("Cannot convert undefined or null to object");
for (var e = Object(t), n = 1; n < arguments.length; n++) {
var r = arguments[n];
if (r !== i && null !== r)
for (var o in r) r.hasOwnProperty(o) && (e[o] = r[o])
}
return e
},
l = function(t) {
var e, n = [];
for (var r in t) t.hasOwnProperty(r) && (e = c(t[r]) ? o(t[r]) : t[r], n.push(encodeURIComponent(r) + "=" + encodeURIComponent(e)));
return n.join("&")
},
p = "addEventListener" in e,
h = p ? "addEventListener" : "attachEvent",
d = p ? "removeEventListener" : "detachEvent",
m = function(t, e, n) {
e = p ? e : "on" + e;
var r = function(i) {
t[d](e, r, !1), n(i)
};
t[h](e, r, !1)
},
v = {
_isFiring: !1,
numOfRequests: 0,
addQueue: function(t) {
this.queue = this.queue.concat(t)
},
queue: [],
isEmpty: function() {
return 0 === this.queue.length
},
complete: function(t) {
return t || this.queue.shift(), this._isFiring = !1, this._fire()
},
_fire: function() {
if (0 !== this.queue.length) {
var t = this.queue[0],
e = t[0] + "?" + l(t[1]);
return this._isFiring = !0, this.numOfRequests++, e.length > 2048 ? this.fireForm(t[0], t[1]) : this.fireImage(e)
}
},
request: function() {
return this.queue.push(Array.prototype.slice.call(arguments)), this._isFiring ? this._isFiring : this._fire()
},
fireForm: function(t, n) {
var r = this,
i = "nio" + Math.random().toString().replace("0.", ""),
a = e.createElement("form"),
u = e.attachEvent && !e.addEventListener,
s = u ? '<iframe name="' + i + '">' : "iframe",
f = e.createElement(s);
a.method = "post", a.action = t, a.target = i, a.acceptCharset = "utf-8", a.style.display = "none", f.src = "javascript:false", f.id = i, f.name = i, a.appendChild(f), m(f, "load", function() {
var t, i = function(t) {
var e = c(t) ? t.type : null;
return a.parentNode.removeChild(a), r.complete("load" !== e)
};
for (var u in n) n.hasOwnProperty(u) && (t = e.createElement("input"), t.name = u, t.value = c(n[u]) ? o(n[u]) : n[u], a.appendChild(t));
m(f, "load", i), m(f, "error", i), a.submit()
}), e.body.appendChild(a)
},
fireImage: function(t) {
var e = new Image,
n = this,
r = function() {
n.complete()
};
return e.onload = r, e.onerror = r, e.src = t, t
}
},
g = {
companyId: null,
options: {
forceSSL: !1,
forcePost: !1
},
getStandardVars: function() {
return {
companyId: this.companyId,
ret: "img",
ts: (new Date).valueOf()
}
},
errors: [],
error: function(t) {
this.errors.push(t)
},
init: function(t, e) {
this.companyId = t, this.config(e)
},
config: function(t) {
for (var e in t) t.hasOwnProperty(e) && (this.options[e] === i && g.error("Narrative.io: " + e + " is not a valid config option"), this.options[e] = t[e])
},
data: function(t) {
return this.submit(t)
},
submit: function(t) {
var e = s();
e = (this.options.forceSSL ? "https:" : n.protocol) + e;
var r = f({}, this.getStandardVars(), t);
return v.request(e, r)
}
};
t.nio._debug = function() {
return [g, v, a]
}, t.nio.execAction = function(t) {
var e = Array.prototype.slice.call(arguments).slice(1);
switch (t) {
case "init":
return g.init.apply(g, e);
case "data":
return g.data.apply(g, e);
default:
return g.error("Narrative.io: " + t + " is not a valid action")
}
}, t.nio.libLoaded = !0, t.nio.libVersion = "1.0", t.nio.isValid = function() {
return 0 === g.errors.length
};
for (var y = t.nio.queue.slice(), S = 0; S < y.length; S++) t.nio.execAction.apply(t.nio, y[S]);
if (y.length = 0, a = null, t.sessionStorage) {
a = function() {
!v.isEmpty() && c(JSON) && "function" == typeof JSON.parse && t.sessionStorage.setItem(u, o(v.queue))
}, m(t, "beforeunload", a, !1);
var b = t.sessionStorage.getItem(u);
if (null !== b) try {
b = JSON.parse(b), v.addQueue(b)
} catch (O) {
g.error("Narrative.io: " + O.message)
} finally {
t.sessionStorage.removeItem(u)
}
}
setTimeout(function(t, e) {
return function() {
0 === e.numOfRequests && t.execAction("data")
}
}(t.nio, v), 250)
}
}(window, document, location, "io.narrative.io");
I am trying to understand what this script intends to do. Google search did not yield any useful information, and the company hosting the js file does not have much information on it. Hoping to get some javascript expert make sense of this.
This was resolved. The hosting company did some more digging and found out from their development team that this was part of a pilot program to collect some analytics data.

Determining saftey of Javascript from other authors, with example

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

How to add delay to _onFormSubmitCompleted function inside MicrosoftAjaxWebForms

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

Categories

Resources