How to decode this url (combination of Base64 and UTF8)? - javascript

I have come across an url that I need to decode.
After trying multiple base64 (utf8), and JS url decoders online, it doesn't help, though the latter did work to an extent.
The url is;
starplayer://%3Curl%3Ebolwl6pIrBrL1GEf7V%2F5Uy6eoFPW77xb5jrS%2BCqRb3%2BoaVq%2Fm3REcqkDQzNsEu2JH6Q2ysUzG73Is93y%2FhmRNK10znrzHKOmEcFITgVDIQeGRVDk7iMBeDth%2BNzmZLIK1yDadYIyBvUPAJ4JRiHzevUVOQ8FMVUJzWAtA5qONGf40KaP31iKvMICFJ3lRjI1cuclOg4KxDo8GeQfmsS7xCAbX1XSWMNlEQ%2Fqzaaht2Gj1fWfbgo%2FsJbGVGSr5swv7ezk4S77LV%2BLpT%2FGbRLbovv0X%2BE4bAQFBtbxfsJ%2BjRU%3D%3Cbase_url%3Ehttp%3A%2F%2Fwww.etoosindia.com%2F%3Cwidth%3E720%3Cheight%3E500%3Ctopmost%3Etrue%3Cresizing%3Eundefined%3Ccookie%3EX2dhPUdBMS4yLjM2NzU5MzMwNS4xNDk4MjExMjczOyBjb29raWVfdWlkPTsgbWVtX25tPVpHOXVkQ0JqWVd4czsgbWVtX2lkPVoyeHdaM1ZvWkdOQWMyaGhjbXRzWVhObGNuTXVZMjl0OyBtZW1fY2Q9TnpreU1EVTU7IF9femxjbWlkPWhBZ1hnVGM4bU1Iekxl%3Ccaption%3ERXRvb3MlMjBJbmRpYQ%3D%3D
After putting the above into a url decoder, I got;
starplayer://<url>bolwl6pIrBrL1GEf7V/5Uy6eoFPW77xb5jrS+CqRb3+oaVq/m3REcqkDQzNsEu2JH6Q2ysUzG73Is93y/hmRNK10znrzHKOmEcFITgVDIQeGRVDk7iMBeDth+NzmZLIK1yDadYIyBvUPAJ4JRiHzevUVOQ8FMVUJzWAtA5qONGf40KaP31iKvMICFJ3lRjI1cuclOg4KxDo8GeQfmsS7xCAbX1XSWMNlEQ/qzaaht2Gj1fWfbgo/sJbGVGSr5swv7ezk4S77LV+LpT/GbRLbovv0X+E4bAQFBtbxfsJ+jRU=<base_url>http://www.etoosindia.com/<width>720<height>500<topmost>true<resizing>undefined<cookie>X2dhPUdBMS4yLjM2NzU5MzMwNS4xNDk4MjExMjczOyBjb29raWVfdWlkPTsgbWVtX25tPVpHOXVkQ0JqWVd4czsgbWVtX2lkPVoyeHdaM1ZvWkdOQWMyaGhjbXRzWVhObGNuTXVZMjl0OyBtZW1fY2Q9TnpreU1EVTU7IF9femxjbWlkPWhBZ1hnVGM4bU1Iekxl<caption>RXRvb3MlMjBJbmRpYQ==
The above url was decoded by a script I am attaching below (see end);
var STARPLAYER_EXE_NOT_INSTALLED = "The StarPlayer is not installed.";
var STARPLAYER_EXE_WANT_TO_INSTALL = "Do you want to install?";
var STARPLAYER_UNKNOWN_INSTALLED = "Has the StarPlayer is running normally?";
var StarPlayerExe = {};
StarPlayerExe.run = function() {
if (typeof this.url == "undefined") {
alert("undefined url");
return
}
var a = this;
StarPlayerLaunchUri(a.getUrl(), function() {
a.result(true, a.install)
}, function() {
a.result(false, a.install)
}, function() {
a.unKnownResult(a.install)
})
}
;
function base_url() {
var b = location.protocol;
var a = location.host;
return b + "//" + a + "/"
}
StarPlayerExe.getUrl = function() {
var a = "<url>" + this.url + "<base_url>" + base_url() + "<width>" + this.width + "<height>" + this.height + "<topmost>" + this.topmost + "<resizing>" + this.resizing + "<cookie>" + Base64.encode(document.cookie) + "<caption>" + Base64.encode(encodeURIComponent(this.caption));
return "starplayer://" + encodeURIComponent(a)
}
;
StarPlayerExe.result = function(a, c) {
if (a == false) {
var b = confirm(STARPLAYER_EXE_NOT_INSTALLED + "\n" + STARPLAYER_EXE_WANT_TO_INSTALL);
if (b == true) {
window.location.href = c
}
}
}
;
StarPlayerExe.unKnownResult = function(b) {
if (COOKIE.get("starplayer_installed") != "true") {
var a = confirm(STARPLAYER_UNKNOWN_INSTALLED);
if (a == true) {
COOKIE.set("starplayer_installed", "true", 60)
} else {
window.location.href = b
}
}
}
;
function StarPlayerLaunchUri(g, d, b, o) {
var s, k, a, j, n, l, m, h, r;
function f(e) {
if (typeof e === "function") {
e()
}
}
function p(t) {
var e;
if (!t) {
t = document.body
}
e = document.createElement("iframe");
e.style.display = "none";
t.appendChild(e);
return e
}
function c(e) {
if (!j) {
return
}
if (!e) {
e = document.body
}
e.removeChild(j);
j = null
}
var i = navigator.appVersion.indexOf("Edge/12") != -1 ? true : false;
r = {
isChrome: false,
isFirefox: false,
isIE: false,
isSafari: false
};
if (window.chrome && !navigator.userAgent.match(/Opera|OPR\//)) {
r.isChrome = true
} else {
if (typeof InstallTrigger !== "undefined") {
r.isFirefox = true
} else {
if (i || "ActiveXObject"in window) {
r.isIE = true
} else {
if (navigator.userAgent.match(/Safari\//)) {
r.isSafari = true
}
}
}
}
if (navigator.msLaunchUri) {
navigator.msLaunchUri(g, d, b)
} else {
if (r.isChrome || r.isSafari) {
m = function() {
window.clearTimeout(l);
window.removeEventListener("blur", m);
f(d)
}
;
h = function() {
window.removeEventListener("blur", m);
f(b)
}
;
window.addEventListener("blur", m);
l = window.setTimeout(h, 1000);
window.location.href = g
} else {
if (r.isFirefox) {
j = p();
try {
j.contentWindow.location.href = g;
f(d)
} catch (q) {
if (q.name === "NS_ERROR_UNKNOWN_PROTOCOL") {
f(b)
} else {
f(o)
}
} finally {
c()
}
} else {
if (r.isIE) {
a = window.open("", "launcher", "width=0,height=0");
a.location.href = g;
try {
a.location.href = "about:blank";
f(d);
n = window.setInterval(function() {
a.close();
if (a.closed) {
window.clearInterval(n)
}
}, 500)
} catch (q) {
a = window.open("about:blank", "launcher");
a.close();
f(b)
}
} else {
j = p();
j.contentWindow.location.href = g;
window.setTimeout(function() {
c(k);
f(o)
}, 1000)
}
}
}
}
}
var COOKIE = {
set: function(g, b, d, c) {
var a = new Date();
var f;
switch (c) {
case "day":
a.setDate(a.getDate() + d);
break;
case "hour":
a.setTime(a.getTime() + (d * 60 * 60 * 1000));
break;
default:
a.setDate(a.getDate() + d)
}
if (d) {
f = escape(b) + "; expires=" + a.toGMTString()
} else {
f = escape(b)
}
document.cookie = g + "=" + f + "; path=/"
},
get: function(g) {
var e = document.cookie.split(";");
var d, c, f, b, a;
b = e.length;
for (d = 0; d < b; d++) {
a = e[d].indexOf("=");
c = e[d].substr(0, a);
f = e[d].substr(a + 1);
c = c.replace(/^\s+|\s+$/g, "");
if (c == g) {
return unescape(f)
}
}
},
del: function(a) {
this.set(a, "", -1)
}
};
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(c) {
var a = "";
var k, h, f, j, g, e, d;
var b = 0;
c = Base64._utf8_encode(c);
while (b < c.length) {
k = c.charCodeAt(b++);
h = c.charCodeAt(b++);
f = c.charCodeAt(b++);
j = k >> 2;
g = ((k & 3) << 4) | (h >> 4);
e = ((h & 15) << 2) | (f >> 6);
d = f & 63;
if (isNaN(h)) {
e = d = 64
} else {
if (isNaN(f)) {
d = 64
}
}
a = a + this._keyStr.charAt(j) + this._keyStr.charAt(g) + this._keyStr.charAt(e) + this._keyStr.charAt(d)
}
return a
},
decode: function(c) {
var a = "";
var k, h, f;
var j, g, e, d;
var b = 0;
c = c.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (b < c.length) {
j = this._keyStr.indexOf(c.charAt(b++));
g = this._keyStr.indexOf(c.charAt(b++));
e = this._keyStr.indexOf(c.charAt(b++));
d = this._keyStr.indexOf(c.charAt(b++));
k = (j << 2) | (g >> 4);
h = ((g & 15) << 4) | (e >> 2);
f = ((e & 3) << 6) | d;
a = a + String.fromCharCode(k);
if (e != 64) {
a = a + String.fromCharCode(h)
}
if (d != 64) {
a = a + String.fromCharCode(f)
}
}
a = Base64._utf8_decode(a);
return a
},
_utf8_encode: function(b) {
b = b.replace(/\r\n/g, "\n");
var a = "";
for (var e = 0; e < b.length; e++) {
var d = b.charCodeAt(e);
if (d < 128) {
a += String.fromCharCode(d)
} else {
if ((d > 127) && (d < 2048)) {
a += String.fromCharCode((d >> 6) | 192);
a += String.fromCharCode((d & 63) | 128)
} else {
a += String.fromCharCode((d >> 12) | 224);
a += String.fromCharCode(((d >> 6) & 63) | 128);
a += String.fromCharCode((d & 63) | 128)
}
}
}
return a
},
_utf8_decode: function(a) {
var b = "";
var d = 0;
var e = c1 = c2 = 0;
while (d < a.length) {
e = a.charCodeAt(d);
if (e < 128) {
b += String.fromCharCode(e);
d++
} else {
if ((e > 191) && (e < 224)) {
c2 = a.charCodeAt(d + 1);
b += String.fromCharCode(((e & 31) << 6) | (c2 & 63));
d += 2
} else {
c2 = a.charCodeAt(d + 1);
c3 = a.charCodeAt(d + 2);
b += String.fromCharCode(((e & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
d += 3
}
}
}
return b
}
};
Can the above code be used to decode this url, and if so, how?
If anyone can help me decode this, I would be very thankful.

Related

setTimeout not working client side on landing page

Good Afternoon, I am trying to have a loading animation for the pages on my site, but the client-side setTimeout function is not working. I have the same function on a test page with no bootstrap and no other scripts and it works, but once I put the script on my landing page it doesn't wait. I have console logged in setTimeout and it does log properly so it's firing, I just don't know why the page isn't waiting. I am using the EJS template engine.
/* 1 */
$(document).ready(function () {
$(window).on('load', function () {
setTimeout(function () {
$("#loader").hide();
}, 5000);
$('#page').show();
});
});
/* 2.
Loading animation javascript */
! function (a, b) {
"use strict";
function c(a) {
a = a || {};
for (var b = 1; b < arguments.length; b++) {
var c = arguments[b];
if (c)
for (var d in c) c.hasOwnProperty(d) && ("object" == typeof c[d] ? deepExtend(a[d], c[d]) : a[d] = c[d])
}
return a
}
function d(d, g) {
function h() {
if (y) {
r = b.createElement("canvas"), r.className = "pg-canvas", r.style.display = "block", d.insertBefore(r, d.firstChild), s = r.getContext("2d"), i();
for (var c = Math.round(r.width * r.height / g.density), e = 0; c > e; e++) {
var f = new n;
f.setStackPos(e), z.push(f)
}
a.addEventListener("resize", function () {
k()
}, !1), b.addEventListener("mousemove", function (a) {
A = a.pageX, B = a.pageY
}, !1), D && !C && a.addEventListener("deviceorientation", function () {
F = Math.min(Math.max(-event.beta, -30), 30), E = Math.min(Math.max(-event.gamma, -30), 30)
}, !0), j(), q("onInit")
}
}
function i() {
r.width = d.offsetWidth, r.height = d.offsetHeight, s.fillStyle = g.dotColor, s.strokeStyle = g.lineColor, s.lineWidth = g.lineWidth
}
function j() {
if (y) {
u = a.innerWidth, v = a.innerHeight, s.clearRect(0, 0, r.width, r.height);
for (var b = 0; b < z.length; b++) z[b].updatePosition();
for (var b = 0; b < z.length; b++) z[b].draw();
G || (t = requestAnimationFrame(j))
}
}
function k() {
i();
for (var a = d.offsetWidth, b = d.offsetHeight, c = z.length - 1; c >= 0; c--)(z[c].position.x > a || z[c].position.y > b) && z.splice(c, 1);
var e = Math.round(r.width * r.height / g.density);
if (e > z.length)
for (; e > z.length;) {
var f = new n;
z.push(f)
} else e < z.length && z.splice(e);
for (c = z.length - 1; c >= 0; c--) z[c].setStackPos(c)
}
function l() {
G = !0
}
function m() {
G = !1, j()
}
function n() {
switch (this.stackPos, this.active = !0, this.layer = Math.ceil(3 * Math.random()), this.parallaxOffsetX = 0, this.parallaxOffsetY = 0, this.position = {
x: Math.ceil(Math.random() * r.width),
y: Math.ceil(Math.random() * r.height)
}, this.speed = {}, g.directionX) {
case "left":
this.speed.x = +(-g.maxSpeedX + Math.random() * g.maxSpeedX - g.minSpeedX).toFixed(2);
break;
case "right":
this.speed.x = +(Math.random() * g.maxSpeedX + g.minSpeedX).toFixed(2);
break;
default:
this.speed.x = +(-g.maxSpeedX / 2 + Math.random() * g.maxSpeedX).toFixed(2), this.speed.x += this.speed.x > 0 ? g.minSpeedX : -g.minSpeedX
}
switch (g.directionY) {
case "up":
this.speed.y = +(-g.maxSpeedY + Math.random() * g.maxSpeedY - g.minSpeedY).toFixed(2);
break;
case "down":
this.speed.y = +(Math.random() * g.maxSpeedY + g.minSpeedY).toFixed(2);
break;
default:
this.speed.y = +(-g.maxSpeedY / 2 + Math.random() * g.maxSpeedY).toFixed(2), this.speed.x += this.speed.y > 0 ? g.minSpeedY : -g.minSpeedY
}
}
function o(a, b) {
return b ? void (g[a] = b) : g[a]
}
function p() {
console.log("destroy"), r.parentNode.removeChild(r), q("onDestroy"), f && f(d).removeData("plugin_" + e)
}
function q(a) {
void 0 !== g[a] && g[a].call(d)
}
var r, s, t, u, v, w, x, y = !!b.createElement("canvas").getContext,
z = [],
A = 0,
B = 0,
C = !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|BB10|mobi|tablet|opera mini|nexus 7)/i),
D = !!a.DeviceOrientationEvent,
E = 0,
F = 0,
G = !1;
return g = c({}, a[e].defaults, g), n.prototype.draw = function () {
s.beginPath(), s.arc(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY, g.particleRadius / 2, 0, 2 * Math.PI, !0), s.closePath(), s.fill(), s.beginPath();
for (var a = z.length - 1; a > this.stackPos; a--) {
var b = z[a],
c = this.position.x - b.position.x,
d = this.position.y - b.position.y,
e = Math.sqrt(c * c + d * d).toFixed(2);
e < g.proximity && (s.moveTo(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY), g.curvedLines ? s.quadraticCurveTo(Math.max(b.position.x, b.position.x), Math.min(b.position.y, b.position.y), b.position.x + b.parallaxOffsetX, b.position.y + b.parallaxOffsetY) : s.lineTo(b.position.x + b.parallaxOffsetX, b.position.y + b.parallaxOffsetY))
}
s.stroke(), s.closePath()
}, n.prototype.updatePosition = function () {
if (g.parallax) {
if (D && !C) {
var a = (u - 0) / 60;
w = (E - -30) * a + 0;
var b = (v - 0) / 60;
x = (F - -30) * b + 0
} else w = A, x = B;
this.parallaxTargX = (w - u / 2) / (g.parallaxMultiplier * this.layer), this.parallaxOffsetX += (this.parallaxTargX - this.parallaxOffsetX) / 10, this.parallaxTargY = (x - v / 2) / (g.parallaxMultiplier * this.layer), this.parallaxOffsetY += (this.parallaxTargY - this.parallaxOffsetY) / 10
}
var c = d.offsetWidth,
e = d.offsetHeight;
switch (g.directionX) {
case "left":
this.position.x + this.speed.x + this.parallaxOffsetX < 0 && (this.position.x = c - this.parallaxOffsetX);
break;
case "right":
this.position.x + this.speed.x + this.parallaxOffsetX > c && (this.position.x = 0 - this.parallaxOffsetX);
break;
default:
(this.position.x + this.speed.x + this.parallaxOffsetX > c || this.position.x + this.speed.x + this.parallaxOffsetX < 0) && (this.speed.x = -this.speed.x)
}
switch (g.directionY) {
case "up":
this.position.y + this.speed.y + this.parallaxOffsetY < 0 && (this.position.y = e - this.parallaxOffsetY);
break;
case "down":
this.position.y + this.speed.y + this.parallaxOffsetY > e && (this.position.y = 0 - this.parallaxOffsetY);
break;
default:
(this.position.y + this.speed.y + this.parallaxOffsetY > e || this.position.y + this.speed.y + this.parallaxOffsetY < 0) && (this.speed.y = -this.speed.y)
}
this.position.x += this.speed.x, this.position.y += this.speed.y
}, n.prototype.setStackPos = function (a) {
this.stackPos = a
}, h(), {
option: o,
destroy: p,
start: m,
pause: l
}
}
var e = "particleground",
f = a.jQuery;
a[e] = function (a, b) {
return new d(a, b)
}, a[e].defaults = {
minSpeedX: .1,
maxSpeedX: .7,
minSpeedY: .1,
maxSpeedY: .7,
directionX: "center",
directionY: "center",
density: 1e4,
dotColor: "#666666",
lineColor: "#666666",
particleRadius: 7,
lineWidth: 1,
curvedLines: !1,
proximity: 100,
parallax: !0,
parallaxMultiplier: 5,
onInit: function () { },
onDestroy: function () { }
}, f && (f.fn[e] = function (a) {
if ("string" == typeof arguments[0]) {
var b, c = arguments[0],
g = Array.prototype.slice.call(arguments, 1);
return this.each(function () {
f.data(this, "plugin_" + e) && "function" == typeof f.data(this, "plugin_" + e)[c] && (b = f.data(this, "plugin_" + e)[c].apply(this, g))
}), void 0 !== b ? b : this
}
return "object" != typeof a && a ? void 0 : this.each(function () {
f.data(this, "plugin_" + e) || f.data(this, "plugin_" + e, new d(this, a))
})
})
}(window, document),
/**
* requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
* #see: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
* #see: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
* #license: MIT license
*/
function () {
for (var a = 0, b = ["ms", "moz", "webkit", "o"], c = 0; c < b.length && !window.requestAnimationFrame; ++c) window.requestAnimationFrame = window[b[c] + "RequestAnimationFrame"], window.cancelAnimationFrame = window[b[c] + "CancelAnimationFrame"] || window[b[c] + "CancelRequestAnimationFrame"];
window.requestAnimationFrame || (window.requestAnimationFrame = function (b) {
var c = (new Date).getTime(),
d = Math.max(0, 16 - (c - a)),
e = window.setTimeout(function () {
b(c + d)
}, d);
return a = c + d, e
}), window.cancelAnimationFrame || (window.cancelAnimationFrame = function (a) {
clearTimeout(a)
})
}();
particleground(document.getElementById('particles-foreground'), {
dotColor: 'rgba(255, 255, 255, 1)',
lineColor: 'rgba(255, 255, 255, 0.05)',
minSpeedX: 0.3,
maxSpeedX: 0.6,
minSpeedY: 0.3,
maxSpeedY: 0.6,
density: 50000, // One particle every n pixels
curvedLines: false,
proximity: 250, // How close two dots need to be before they join
parallaxMultiplier: 10, // Lower the number is more extreme parallax
particleRadius: 4, // Dot size
});
particleground(document.getElementById('particles-background'), {
dotColor: 'rgba(255, 255, 255, 0.5)',
lineColor: 'rgba(255, 255, 255, 0.05)',
minSpeedX: 0.075,
maxSpeedX: 0.15,
minSpeedY: 0.075,
maxSpeedY: 0.15,
density: 30000, // One particle every n pixels
curvedLines: false,
proximity: 20, // How close two dots need to be before they join
parallaxMultiplier: 20, // Lower the number is more extreme parallax
particleRadius: 2, // Dot size
});
p {
background: lightgray;
margin: 0
}
p::before {
content: "Placeholder for: "
}
#loader {
background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<p><%- include('layouts/head'); -%></p>
<p><%- include('layouts/index/index-style'); -%> </p>
<p><%- include('layouts/index/google-analytics'); -%></p>
</head>
<body>
<div id="loader">
<div id="particles-background" class="vertical-centered-box"></div>
<div id="particles-foreground" class="vertical-centered-box"></div>
<div class="vertical-centered-box">
<div class="content">
<div class="loader-circle"></div>
<div class="loader-line-mask">
<div class="loader-line"></div>
</div>
<p><%- include('layouts/payment/paymentCanceled-svg'); -%></p>
</div>
</div>
</div>
<div id="page" class="container">
(page content is located within this container using bootstrap)
</div>
<p><%- include('layouts/footer'); -%></p>
<p><%- include('layouts/scripts'); -%></p>
</body>
</html>
I found that setTimeout was not the function I was looking for because my app was not waiting for the page to load. I instead used the below and it worked!
document.onreadystatechange = function () {
if (document.readyState !== "complete") {
document.querySelector("body").style.visibility = "hidden";
document.querySelector("#loader").style.visibility = "visible";
} else {
document.querySelector("#loader").style.display = "none";
document.querySelector("body").style.visibility = "visible";
}
};

equations with 3 numbers not displaying on HTML

I'm writing a math problem generator, but when I run it only equations with 2 numbers are displayed, anything more and it says "undefined" and refuses to show the answer. Here is the entire code(please note it is incomplete right now)
var type = 0;
var ans = 0;
function generatenumeral() {
var num = (Math.round(1000 * Math.random())) / 100;
var abs = Math.random();
if (abs < .4) {
num = num * -1;
}
console.log(num);
return (num);
}
function generatelength() {
var num = (Math.ceil(3 * Math.random()));
console.log(num);
return (num);
}
function generateSymbol() {
var sign = 0;
var num = (Math.round(12 * Math.random()));
console.log(num);
if (num === 0 || num == 1 || num == 9) {
sign = "+";
};
if (num === 2 || num == 3 || num == 10) {
sign = "-";
};
if (num === 4 || num == 5 || num == 11) {
sign = "/";
};
if (num === 6 || num == 7 || num == 12) {
sign = "*";
};
if (num == 8) {
sign = "+";
};
return (sign);
}
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
function twoNumb() {
var sign = 0;
var equation = 0;
var a = generatenumeral();
var b = generatenumeral();
var siggn = generateSymbol();
equation = a + " " + siggn + " " + b;
if (siggn == "+") {
ans = a + b;
}
if (siggn == "-") {
ans = a - b;
}
if (siggn == "/") {
ans = a / b;
}
if (siggn == "*") {
ans = a * b;
}
return (equation);
}
function threNumb() {
var sign = 0;
var a = generatenumeral();
var b = generatenumeral();
var c = generatenumeral();
var siggn = generateSymbol();
var siggnA = generateSymbol();
var equation = a + " " + siggn + " " + b +" "+ siggnA +" "+ c;
if (siggn.equals("+")) {
if (siggna.equals("+")) {
ans = a + b + c;
}
if (siggna.equals("-")) {
ans = (a + b) - c;
}
if (siggna.equals("/")) {
ans = a + (b / c);
}
if (siggna.equals("*")) {
ans = a + (b * c);
}
}
if (siggn.equals("-")) {
if (siggna.equals("+")) {
ans = a - b + c;
}
if (siggna.equals("-")) {
ans = (a - b) - c;
}
if (siggna == "/") {
ans = a - (b / c);
}
if (siggna.equals("*")) {
ans = a - (b * c);
}
}
if (siggn.equals("/")) {
if (siggna.equals("+")) {
ans = (a / b) + c;
}
if (siggna.equals("-")) {
ans = (a / b) - c;
}
if (siggna.equals("/")) {
ans = (a / b) / c;
}
if (siggna.equals("*")) {
ans = (a / b) * c;
}
}
if (siggn.equals("*")) {
if (siggna.equals("+")) {
ans = (a * b) + c;
}
if (siggna.equals("-")) {
ans = (a * b) - c;
}
if (siggna.equals("/")) {
ans = (a * b) / c;
}
if (siggna.equals("*")) {
ans = (a * b) * c;
}
}
// if (siggn == "^") {
// var ba = Math.round(b);
// var count = 0;
// for (count = 0; count < ba; count += 1) {
// var ab = ab * a;
// }
// ans = ab;
return (equation);
}
document.getElementById("ans").innerHTML = "not yet";
function arithmetic() {
type = 1;
document.getElementById("demo").innerHTML = WarmUpAr();
}
function preAlg() {
type = 2;
document.getElementById("demo").innerHTML = "hello";
}
function Alg() {
type = 3;
document.getElementById("demo").innerHTML = "This is cool";
}
function theAns() {
document.getElementById("ans").innerHTML = ans;
}
<p> "your warm up is....." </p>
<button onclick="arithmetic()">Arithmetic Warm Up </button>
<button onclick="preAlg()">PreAlg Warm Up </button>
<button onclick="Alg()">Algerbra Warm Up </button>
<p id="demo"></p>
<p>the answer is ....</p>
<button onclick="theAns()">answer</button>
<p id="ans"></p>
You forgot to close the WarmUpAr funtion,that's why you are getting undefined error
close this function WarmUpAr();
function WarmUpAr() {
var leng = generatelength();
if (leng == 1) {
var cool = twoNumb();
return (cool);
}
if (leng == 2) {
var cool = threNumb();
return (cool);
}
}
The reason threNumb() is failing is because your calling siggna.equals() in all your if statements. twoNumb() works because your using == instead of equals().
Also, in terms of calculating the answer to the equation, your doing it the hard way. In twoNumb() and threNumb() everything between where you set the 'equation' variable and where you return the 'equation' can be replaced with:
ans = eval(equation);

Javascript Escape All But Text Related HTML Tags (<h1>, <p>, <img> etc.)

Using Javascript & jQuery, how can I escape all HTML except content related tags such as H1, img etc? I have converted markdown text to HTML and put this inside a div, but I do not want my users writing <script> tags, <div>'s or any kind of exploit.
Is there a way I can safely use html converted from markdown on my website?
(A great example is stackoverflow, this text is using markdown but does not allow me to exploit it with <script>alert("Hi");</script>)
EDIT: I have uploaded this method to my github. Read README for information on usage. View my markdown2html repo here.
One method I have came up with is using the marked package on github combined with a custom made function.
After including the marked JS code (located at the bottom of this answer) you can use the following function I have made to escape all HTML tags within markdown except those within code tags (``).
Here is the function I have written in pure javascript combined with the marked package on github;
// INCLUDE MARKED JS CODE (LINK ABOVE) BEFORE USING THIS FUNCTION
function markdownToHTML(markdown) {
// Define variables
var re = /``.*?``/g,
str = markdown,
lastIndex = 0,
escaped = "";
// Escape <, > and & from non-code markdown
while ((match = re.exec(str)) != null) {
// Define variables to escape and to leave
var dangerous = markdown.substring(lastIndex, match.index);
var safe = match[0];
// Escape dangerous markdown
dangerous = dangerous.replace(/<[^>]+>/g, function(wholeMatch, innerTag) {
while (wholeMatch.charAt(0) == "<")
wholeMatch = wholeMatch.replace("<", "<");
while (wholeMatch.charAt(wholeMatch.length - 1) == ">")
wholeMatch = wholeMatch.replace(/.$/, ">");
return wholeMatch;
});
// Add escaped strings to new escaped string
escaped += dangerous;
escaped += safe;
// Set lastIndex to end index of match
lastIndex = match.index + match[0].length;
}
escaped += markdown.substring(lastIndex, markdown.length).replace(/<[^>]+>/g, function(wholeMatch, innerTag) {
while (wholeMatch.charAt(0) == "<")
wholeMatch = wholeMatch.replace("<", "<");
while (wholeMatch.charAt(wholeMatch.length - 1) == ">")
wholeMatch = wholeMatch.replace(/.$/, ">");
return wholeMatch;
});
// Return SAFE markdown and convert to HTML
return marked(escaped);
}
To use this function, simply call it with the first argument being the markdown you want to safely convert to HTML. Here is an example;
document.body.innerHTML = markdownToHTML("This **text** should be escaped.\nIf I try to create a div by using:\n<div style='width:100px;height:100px;background-color:red;'>My Div</div>\nit will be escaped...\n\nWhere as if I use it in a code section like so:\n``<div style='width:100px;height:100px;background-color:red;'>My Div</div>``\nit should be left alone and **not** escaped.");
Output:
Use this JS code "Marked" from github to use the marked() function
Complete code snippet:
// Include marked
(function() { function e(e) { this.tokens = [], this.tokens.links = {}, this.options = e || a.defaults, this.rules = p.normal, this.options.gfm && (this.options.tables ? this.rules = p.tables : this.rules = p.gfm) } function t(e, t) { if (this.options = t || a.defaults, this.links = e, this.rules = u.normal, this.renderer = this.options.renderer || new n, this.renderer.options = this.options, !this.links) throw new Error("Tokens array requires a `links` property."); this.options.gfm ? this.options.breaks ? this.rules = u.breaks : this.rules = u.gfm : this.options.pedantic && (this.rules = u.pedantic) } function n(e) { this.options = e || {} } function r(e) { this.tokens = [], this.token = null, this.options = e || a.defaults, this.options.renderer = this.options.renderer || new n, this.renderer = this.options.renderer, this.renderer.options = this.options } function s(e, t) { return e.replace(t ? /&/g : /&(?!#?\w+;)/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'") } function i(e) { return e.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(e, t) { return t = t.toLowerCase(), "colon" === t ? ":" : "#" === t.charAt(0) ? "x" === t.charAt(1) ? String.fromCharCode(parseInt(t.substring(2), 16)) : String.fromCharCode(+t.substring(1)) : "" }) } function l(e, t) { return e = e.source, t = t || "", function n(r, s) { return r ? (s = s.source || s, s = s.replace(/(^|[^\[])\^/g, "$1"), e = e.replace(r, s), n) : new RegExp(e, t) } } function o() { } function h(e) { for (var t, n, r = 1; r < arguments.length; r++){ t = arguments[r]; for (n in t) Object.prototype.hasOwnProperty.call(t, n) && (e[n] = t[n]) } return e } function a(t, n, i) { if (i || "function" == typeof n) { i || (i = n, n = null), n = h({}, a.defaults, n || {}); var l, o, p = n.highlight, u = 0; try { l = e.lex(t, n) } catch (c) { return i(c) } o = l.length; var g = function(e) { if (e) return n.highlight = p, i(e); var t; try { t = r.parse(l, n) } catch (s) { e = s } return n.highlight = p, e ? i(e) : i(null, t) }; if (!p || p.length < 3) return g(); if (delete n.highlight, !o) return g(); for (; u < l.length; u++)!function(e) { return "code" !== e.type ? --o || g() : p(e.text, e.lang, function(t, n) { return t ? g(t) : null == n || n === e.text ? --o || g() : (e.text = n, e.escaped = !0, void (--o || g())) }) } (l[u]) } else try { return n && (n = h({}, a.defaults, n)), r.parse(e.lex(t, n), n) } catch (c) { if (c.message += "\nPlease report this to https://github.com/chjj/marked.", (n || a.defaults).silent) return "<p>An error occured:</p><pre>" + s(c.message + "", !0) + "</pre>"; throw c } } var p = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: o, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: o, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: o, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/ }; p.bullet = /(?:[*+-]|\d+\.)/, p.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/, p.item = l(p.item, "gm")(/bull/g, p.bullet)(), p.list = l(p.list)(/bull/g, p.bullet)("hr", "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def", "\\n+(?=" + p.def.source + ")")(), p.blockquote = l(p.blockquote)("def", p.def)(), p._tag = "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s#]*#)\\b", p.html = l(p.html)("comment", /<!--[\s\S]*?-->/)("closed", /<(tag)[\s\S]+?<\/\1>/)("closing", /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, p._tag)(), p.paragraph = l(p.paragraph)("hr", p.hr)("heading", p.heading)("lheading", p.lheading)("blockquote", p.blockquote)("tag", "<" + p._tag)("def", p.def)(), p.normal = h({}, p), p.gfm = h({}, p.normal, { fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, paragraph: /^/, heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ }), p.gfm.paragraph = l(p.paragraph)("(?!", "(?!" + p.gfm.fences.source.replace("\\1", "\\2") + "|" + p.list.source.replace("\\1", "\\3") + "|")(), p.tables = h({}, p.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ }), e.rules = p, e.lex = function(t, n) { var r = new e(n); return r.lex(t) }, e.prototype.lex = function(e) { return e = e.replace(/\r\n|\r/g, "\n").replace(/\t/g, " ").replace(/\u00a0/g, " ").replace(/\u2424/g, "\n"), this.token(e, !0) }, e.prototype.token = function(e, t, n) { for (var r, s, i, l, o, h, a, u, c, e = e.replace(/^ +$/gm, ""); e;)if ((i = this.rules.newline.exec(e)) && (e = e.substring(i[0].length), i[0].length > 1 && this.tokens.push({ type: "space" })), i = this.rules.code.exec(e)) e = e.substring(i[0].length), i = i[0].replace(/^ {4}/gm, ""), this.tokens.push({ type: "code", text: this.options.pedantic ? i : i.replace(/\n+$/, "") }); else if (i = this.rules.fences.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "code", lang: i[2], text: i[3] || "" }); else if (i = this.rules.heading.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "heading", depth: i[1].length, text: i[2] }); else if (t && (i = this.rules.nptable.exec(e))) { for (e = e.substring(i[0].length), h = { type: "table", header: i[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: i[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: i[3].replace(/\n$/, "").split("\n") }, u = 0; u < h.align.length; u++)/^ *-+: *$/.test(h.align[u]) ? h.align[u] = "right" : /^ *:-+: *$/.test(h.align[u]) ? h.align[u] = "center" : /^ *:-+ *$/.test(h.align[u]) ? h.align[u] = "left" : h.align[u] = null; for (u = 0; u < h.cells.length; u++)h.cells[u] = h.cells[u].split(/ *\| */); this.tokens.push(h) } else if (i = this.rules.lheading.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "heading", depth: "=" === i[2] ? 1 : 2, text: i[1] }); else if (i = this.rules.hr.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "hr" }); else if (i = this.rules.blockquote.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "blockquote_start" }), i = i[0].replace(/^ *> ?/gm, ""), this.token(i, t, !0), this.tokens.push({ type: "blockquote_end" }); else if (i = this.rules.list.exec(e)) { for (e = e.substring(i[0].length), l = i[2], this.tokens.push({ type: "list_start", ordered: l.length > 1 }), i = i[0].match(this.rules.item), r = !1, c = i.length, u = 0; c > u; u++)h = i[u], a = h.length, h = h.replace(/^ *([*+-]|\d+\.) +/, ""), ~h.indexOf("\n ") && (a -= h.length, h = this.options.pedantic ? h.replace(/^ {1,4}/gm, "") : h.replace(new RegExp("^ {1," + a + "}", "gm"), "")), this.options.smartLists && u !== c - 1 && (o = p.bullet.exec(i[u + 1])[0], l === o || l.length > 1 && o.length > 1 || (e = i.slice(u + 1).join("\n") + e, u = c - 1)), s = r || /\n\n(?!\s*$)/.test(h), u !== c - 1 && (r = "\n" === h.charAt(h.length - 1), s || (s = r)), this.tokens.push({ type: s ? "loose_item_start" : "list_item_start" }), this.token(h, !1, n), this.tokens.push({ type: "list_item_end" }); this.tokens.push({ type: "list_end" }) } else if (i = this.rules.html.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: this.options.sanitize ? "paragraph" : "html", pre: !this.options.sanitizer && ("pre" === i[1] || "script" === i[1] || "style" === i[1]), text: i[0] }); else if (!n && t && (i = this.rules.def.exec(e))) e = e.substring(i[0].length), this.tokens.links[i[1].toLowerCase()] = { href: i[2], title: i[3] }; else if (t && (i = this.rules.table.exec(e))) { for (e = e.substring(i[0].length), h = { type: "table", header: i[1].replace(/^ *| *\| *$/g, "").split(/ *\| */), align: i[2].replace(/^ *|\| *$/g, "").split(/ *\| */), cells: i[3].replace(/(?: *\| *)?\n$/, "").split("\n") }, u = 0; u < h.align.length; u++)/^ *-+: *$/.test(h.align[u]) ? h.align[u] = "right" : /^ *:-+: *$/.test(h.align[u]) ? h.align[u] = "center" : /^ *:-+ *$/.test(h.align[u]) ? h.align[u] = "left" : h.align[u] = null; for (u = 0; u < h.cells.length; u++)h.cells[u] = h.cells[u].replace(/^ *\| *| *\| *$/g, "").split(/ *\| */); this.tokens.push(h) } else if (t && (i = this.rules.paragraph.exec(e))) e = e.substring(i[0].length), this.tokens.push({ type: "paragraph", text: "\n" === i[1].charAt(i[1].length - 1) ? i[1].slice(0, -1) : i[1] }); else if (i = this.rules.text.exec(e)) e = e.substring(i[0].length), this.tokens.push({ type: "text", text: i[0] }); else if (e) throw new Error("Infinite loop on byte: " + e.charCodeAt(0)); return this.tokens }; var u = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ >]+(#|:\/)[^ >]+)>/, url: o, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: o, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/ }; u._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/, u._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/, u.link = l(u.link)("inside", u._inside)("href", u._href)(), u.reflink = l(u.reflink)("inside", u._inside)(), u.normal = h({}, u), u.pedantic = h({}, u.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ }), u.gfm = h({}, u.normal, { escape: l(u.escape)("])", "~|])")(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: l(u.text)("]|", "~]|")("|", "|https?://|")() }), u.breaks = h({}, u.gfm, { br: l(u.br)("{2,}", "*")(), text: l(u.gfm.text)("{2,}", "*")() }), t.rules = u, t.output = function(e, n, r) { var s = new t(n, r); return s.output(e) }, t.prototype.output = function(e) { for (var t, n, r, i, l = ""; e;)if (i = this.rules.escape.exec(e)) e = e.substring(i[0].length), l += i[1]; else if (i = this.rules.autolink.exec(e)) e = e.substring(i[0].length), "#" === i[2] ? (n = ":" === i[1].charAt(6) ? this.mangle(i[1].substring(7)) : this.mangle(i[1]), r = this.mangle("mailto:") + n) : (n = s(i[1]), r = n), l += this.renderer.link(r, null, n); else if (this.inLink || !(i = this.rules.url.exec(e))) { if (i = this.rules.tag.exec(e)) !this.inLink && /^<a /i.test(i[0]) ? this.inLink = !0 : this.inLink && /^<\/a>/i.test(i[0]) && (this.inLink = !1), e = e.substring(i[0].length), l += this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(i[0]) : s(i[0]) : i[0]; else if (i = this.rules.link.exec(e)) e = e.substring(i[0].length), this.inLink = !0, l += this.outputLink(i, { href: i[2], title: i[3] }), this.inLink = !1; else if ((i = this.rules.reflink.exec(e)) || (i = this.rules.nolink.exec(e))) { if (e = e.substring(i[0].length), t = (i[2] || i[1]).replace(/\s+/g, " "), t = this.links[t.toLowerCase()], !t || !t.href) { l += i[0].charAt(0), e = i[0].substring(1) + e; continue } this.inLink = !0, l += this.outputLink(i, t), this.inLink = !1 } else if (i = this.rules.strong.exec(e)) e = e.substring(i[0].length), l += this.renderer.strong(this.output(i[2] || i[1])); else if (i = this.rules.em.exec(e)) e = e.substring(i[0].length), l += this.renderer.em(this.output(i[2] || i[1])); else if (i = this.rules.code.exec(e)) e = e.substring(i[0].length), l += this.renderer.codespan(s(i[2], !0)); else if (i = this.rules.br.exec(e)) e = e.substring(i[0].length), l += this.renderer.br(); else if (i = this.rules.del.exec(e)) e = e.substring(i[0].length), l += this.renderer.del(this.output(i[1])); else if (i = this.rules.text.exec(e)) e = e.substring(i[0].length), l += this.renderer.text(s(this.smartypants(i[0]))); else if (e) throw new Error("Infinite loop on byte: " + e.charCodeAt(0)) } else e = e.substring(i[0].length), n = s(i[1]), r = n, l += this.renderer.link(r, null, n); return l }, t.prototype.outputLink = function(e, t) { var n = s(t.href), r = t.title ? s(t.title) : null; return "!" !== e[0].charAt(0) ? this.renderer.link(n, r, this.output(e[1])) : this.renderer.image(n, r, s(e[1])) }, t.prototype.smartypants = function(e) { return this.options.smartypants ? e.replace(/---/g, "—").replace(/--/g, "–").replace(/(^|[-\u2014\/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014\/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…") : e }, t.prototype.mangle = function(e) { if (!this.options.mangle) return e; for (var t, n = "", r = e.length, s = 0; r > s; s++)t = e.charCodeAt(s), Math.random() > .5 && (t = "x" + t.toString(16)), n += "&#" + t + ";"; return n }, n.prototype.code = function(e, t, n) { if (this.options.highlight) { var r = this.options.highlight(e, t); null != r && r !== e && (n = !0, e = r) } return t ? '<pre><code class="' + this.options.langPrefix + s(t, !0) + '">' + (n ? e : s(e, !0)) + "\n</code></pre>\n" : "<pre><code>" + (n ? e : s(e, !0)) + "\n</code></pre>" }, n.prototype.blockquote = function(e) { return "<blockquote>\n" + e + "</blockquote>\n" }, n.prototype.html = function(e) { return e }, n.prototype.heading = function(e, t, n) { return "<h" + t + ' id="' + this.options.headerPrefix + n.toLowerCase().replace(/[^\w]+/g, "-") + '">' + e + "</h" + t + ">\n" }, n.prototype.hr = function() { return this.options.xhtml ? "<hr/>\n" : "<hr>\n" }, n.prototype.list = function(e, t) { var n = t ? "ol" : "ul"; return "<" + n + ">\n" + e + "</" + n + ">\n" }, n.prototype.listitem = function(e) { return "<li>" + e + "</li>\n" }, n.prototype.paragraph = function(e) { return "<p>" + e + "</p>\n" }, n.prototype.table = function(e, t) { return "<table>\n<thead>\n" + e + "</thead>\n<tbody>\n" + t + "</tbody>\n</table>\n" }, n.prototype.tablerow = function(e) { return "<tr>\n" + e + "</tr>\n" }, n.prototype.tablecell = function(e, t) { var n = t.header ? "th" : "td", r = t.align ? "<" + n + ' style="text-align:' + t.align + '">' : "<" + n + ">"; return r + e + "</" + n + ">\n" }, n.prototype.strong = function(e) { return "<strong>" + e + "</strong>" }, n.prototype.em = function(e) { return "<em>" + e + "</em>" }, n.prototype.codespan = function(e) { return "<code>" + e + "</code>" }, n.prototype.br = function() { return this.options.xhtml ? "<br/>" : "<br>" }, n.prototype.del = function(e) { return "<del>" + e + "</del>" }, n.prototype.link = function(e, t, n) { if (this.options.sanitize) { try { var r = decodeURIComponent(i(e)).replace(/[^\w:]/g, "").toLowerCase() } catch (s) { return "" } if (0 === r.indexOf("javascript:") || 0 === r.indexOf("vbscript:")) return "" } var l = '" + n + "" }, n.prototype.image = function(e, t, n) { var r = '<img src="' + e + '" alt="' + n + '"'; return t && (r += ' title="' + t + '"'), r += this.options.xhtml ? "/>" : ">" }, n.prototype.text = function(e) { return e }, r.parse = function(e, t, n) { var s = new r(t, n); return s.parse(e) }, r.prototype.parse = function(e) { this.inline = new t(e.links, this.options, this.renderer), this.tokens = e.reverse(); for (var n = ""; this.next();)n += this.tok(); return n }, r.prototype.next = function() { return this.token = this.tokens.pop() }, r.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0 }, r.prototype.parseText = function() { for (var e = this.token.text; "text" === this.peek().type;)e += "\n" + this.next().text; return this.inline.output(e) }, r.prototype.tok = function() { switch (this.token.type) { case "space": return ""; case "hr": return this.renderer.hr(); case "heading": return this.renderer.heading(this.inline.output(this.token.text), this.token.depth, this.token.text); case "code": return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); case "table": var e, t, n, r, s, i = "", l = ""; for (n = "", e = 0; e < this.token.header.length; e++)r = { header: !0, align: this.token.align[e] }, n += this.renderer.tablecell(this.inline.output(this.token.header[e]), { header: !0, align: this.token.align[e] }); for (i += this.renderer.tablerow(n), e = 0; e < this.token.cells.length; e++){ for (t = this.token.cells[e], n = "", s = 0; s < t.length; s++)n += this.renderer.tablecell(this.inline.output(t[s]), { header: !1, align: this.token.align[s] }); l += this.renderer.tablerow(n) } return this.renderer.table(i, l); case "blockquote_start": for (var l = ""; "blockquote_end" !== this.next().type;)l += this.tok(); return this.renderer.blockquote(l); case "list_start": for (var l = "", o = this.token.ordered; "list_end" !== this.next().type;)l += this.tok(); return this.renderer.list(l, o); case "list_item_start": for (var l = ""; "list_item_end" !== this.next().type;)l += "text" === this.token.type ? this.parseText() : this.tok(); return this.renderer.listitem(l); case "loose_item_start": for (var l = ""; "list_item_end" !== this.next().type;)l += this.tok(); return this.renderer.listitem(l); case "html": var h = this.token.pre || this.options.pedantic ? this.token.text : this.inline.output(this.token.text); return this.renderer.html(h); case "paragraph": return this.renderer.paragraph(this.inline.output(this.token.text)); case "text": return this.renderer.paragraph(this.parseText()) } }, o.exec = o, a.options = a.setOptions = function(e) { return h(a.defaults, e), a }, a.defaults = { gfm: !0, tables: !0, breaks: !1, pedantic: !1, sanitize: !1, sanitizer: null, mangle: !0, smartLists: !1, silent: !1, highlight: null, langPrefix: "lang-", smartypants: !1, headerPrefix: "", renderer: new n, xhtml: !1 }, a.Parser = r, a.parser = r.parse, a.Renderer = n, a.Lexer = e, a.lexer = e.lex, a.InlineLexer = t, a.inlineLexer = t.output, a.parse = a, "undefined" != typeof module && "object" == typeof exports ? module.exports = a : "function" == typeof define && define.amd ? define(function() { return a }) : this.marked = a }).call(function() { return this || ("undefined" != typeof window ? window : global) } ());
function markdownToHTML(markdown) {
// Define variables
var re = /``.*?``/g,
str = markdown,
lastIndex = 0,
escaped = "";
// Escape <, > and & from non-code markdown
while ((match = re.exec(str)) != null) {
// Define variables to escape and to leave
var dangerous = markdown.substring(lastIndex, match.index);
var safe = match[0];
// Escape dangerous markdown
dangerous = dangerous.replace(/<[^>]+>/g, function(wholeMatch, innerTag) {
while (wholeMatch.charAt(0) == "<")
wholeMatch = wholeMatch.replace("<", "<");
while (wholeMatch.charAt(wholeMatch.length - 1) == ">")
wholeMatch = wholeMatch.replace(/.$/, ">");
return wholeMatch;
});
// Add escaped strings to new escaped string
escaped += dangerous;
escaped += safe;
// Set lastIndex to end index of match
lastIndex = match.index + match[0].length;
}
escaped += markdown.substring(lastIndex, markdown.length).replace(/<[^>]+>/g, function(wholeMatch, innerTag) {
while (wholeMatch.charAt(0) == "<")
wholeMatch = wholeMatch.replace("<", "<");
while (wholeMatch.charAt(wholeMatch.length - 1) == ">")
wholeMatch = wholeMatch.replace(/.$/, ">");
return wholeMatch;
});
// Return SAFE markdown and convert to HTML
return marked(escaped);
}
document.getElementById("converted-markdown").innerHTML = markdownToHTML("This **text** should be escaped.\nIf I try to create a div by using:\n<div style='width:100px;height:100px;background-color:red;'>My Div</div>\nit will be escaped...\n\nWhere as if I use it in a code section like so:\n``<div style='width:100px;height:100px;background-color:red;'>My Div</div>``\nit should be left alone and **not** escaped.");
<div id="converted-markdown"></div>

Uncaught TypeError: Cannot read property 'getSelection' of null

I am using following code to simulate mouse click event on an element.
var composeEl = $('.asf.T-I-J3.J-J5-Ji:visible')[0];
if (composeEl) {
//Trigger mouse down event
var mouseDown = document.createEvent('MouseEvents');
mouseDown.initEvent('mousedown', true, false);
composeEl.dispatchEvent(mouseDown)
//Trigger mouse up event
var mouseUp = document.createEvent('MouseEvents');
mouseUp.initEvent('mouseup', true, false);
composeEl.dispatchEvent(mouseUp)
}
it works fine, its clicking but throw this error in console
Uncaught TypeError: Cannot read property 'getSelection' of null.
What is wrong with this javascript code?
Chrome show error in content.js file. I am not including this file.
error is on this line
var c=b.view.getSelection(); in below code
var m;if (!window.a) {
var t = function() {
var b = window.self === window.top;
this.k = (this.G = b) ? 0 : null;
this.s = this.d = !1;
this.j = this.i = -1;
this.F = 1;
this.c = {};
this.q = [];
var c = chrome.extension.connect({
name: b ? "top" : "sub"
});
this.a = c;
this.r = c.a || Math.ceil(975 * Math.random());
c.onMessage.addListener(this.onMessage.bind(this));
c.onDisconnect.addListener(this.v.bind(this));
this.b(window, "scroll", this.O, !0);
this.b(window, "keydown", this.u, !0);
this.b(window, "keyup", this.u, !0);
this.b(window, "mousedown", this.L, !0);
this.b(window, "mouseup",
this.M, !0);
this.b(window, "blur", this.K, !0);
this.b(document, "beforeload", this.I, !0);
this.b(document, "DOMContentLoaded", this.J);
b && this.b(window, "resize", this.N)
};
window.a = !0;
var x = {
16: !0,
17: !0,
18: !0,
45: !0,
46: !0
},
C = ["VIDEO", "AUDIO", "OBJECT", "EMBED"],
D = new RegExp(atob("eXRwbGF5ZXJcLmNvbmZpZ1xzKj1ccypcew=="));
m = t.prototype;
m.A = function(b, c, e, f) {
try {
var d = document.activeElement,
n = d && 0 <= C.indexOf(d.tagName) ? d : null;
n || (n = (d = document.elementFromPoint(this.i, this.j)) && 0 <= C.indexOf(d.tagName) ? d : null);
for (var k =
0, p, q, r, h, l = 0; l < C.length; l++) {
for (var g = document.getElementsByTagName(C[l]), w = 0; w < g.length; w++)
if (d = g[w], 3 != l || "application/x-shockwave-flash" == d.type.toLowerCase()) {
var s = d.src || d.data;
if (s && (s == b || s == c)) {
p = d;
break
}
if (!n && !q)
if (!s || s != e && s != f) {
var u = d.clientWidth,
v = d.clientHeight;
if (u && v) {
var y = d.getBoundingClientRect();
if (!(0 >= y.right + window.scrollX || 0 >= y.bottom + window.scrollY)) {
var z = window.getComputedStyle(d);
if (!z || "hidden" != z.visibility) {
var A = u * v;
A > k && 1.35 * u > v && u < 3 * v && (k = A, r = d);
h || (h = d)
}
}
}
} else q =
d
}
if (p) break
}
b = p || n || q || r || h;
if (!b) return null;
if ("EMBED" == b.tagName && !b.clientWidth && !b.clientHeight) {
var B = b.parentElement;
"OBJECT" == B.tagName && (b = B)
}
return this.g(b)
} catch (E) {}
};
m.w = function(b, c, e) {
try {
for (var f = [], d, f = Array.prototype.concat.apply(f, document.getElementsByTagName("FRAME")), f = Array.prototype.concat.apply(f, document.getElementsByTagName("IFRAME")), n = 0; n < f.length; n++) {
var k = f[n];
if (parseInt(k.getAttribute("__idm_frm__")) == b) {
d = k;
break
}
if (!d) {
var p = k.src;
!p || p != c && p != e || (d = k)
}
}
return this.g(d)
} catch (q) {}
};
m.p = function() {
var b = window.devicePixelRatio,
c = document.width,
e = document.body.scrollWidth;
c && e && (b = c == e ? 0 : c / e);
return b
};
m.n = function(b) {
try {
var c = b.getBoundingClientRect(),
e = Math.round(c.width),
f = Math.round(c.height);
if (15 > e || 15 > f) return null;
var d = document.documentElement,
n = d.scrollHeight || d.clientHeight,
k = Math.round(c.left) + b.clientLeft,
p = Math.round(c.top) + b.clientTop;
return k >= (d.scrollWidth || d.clientWidth) || p >= n ? null : {
left: k,
top: p,
right: k + e,
bottom: p + f,
zoom: this.p()
}
} catch (q) {}
};
m.o = function() {
this.a.postMessage([21,
window.location.href
])
};
m.f = function(b) {
if (b) {
if (!this.H) {
this.H = !0;
this.b(window, "message", this.P);
var c = document.createElement("script");
c.src = chrome.extension.getURL("document.js");
c.onload = function() {
c.parentNode.removeChild(c)
};
document.documentElement.appendChild(c)
}
window.setTimeout(function() {
window.postMessage([1], "/")
}, 3E3)
} else if ("loading" == document.readyState) this.t = !0;
else {
this.t = !1;
b = document.getElementsByTagName("SCRIPT");
for (var e = 0; e < b.length; e++)
if (c = b[e], !c.src && D.test(c.innerText)) {
b =
this.h();
this.a.postMessage([34, b, -1, c.outerHTML]);
break
}
}
};
m.P = function(b) {
var c = b.data;
c instanceof Array && b.origin == (document.origin || location.origin) && 2 == c[0] && this.a.postMessage([34, c[1], -1, c[2]])
};
m.D = function(b) {
var c = b[2] || this.w(b[3], b[4], b[5]),
e = c && this.c[c],
e = e && this.n(e);
this.a.postMessage([22, b[1], b[3], c, e])
};
m.C = function(b) {
var c = !b[2],
e = b[2] || this.A(b[3], b[4], b[5], b[6]);
b = [23, b[1], e, !1];
var f = e && this.c[e];
if (f) {
var d = this.n(f);
d && (b[4] = d);
c ? (b[5] = f.tagName, b[6] = f.src || f.data, b[7] = this.h()) :
d || document.contains(f) || (b[3] = !0, delete this.c[e])
}
this.a.postMessage(b)
};
m.g = function(b) {
try {
var c = parseInt(b.getAttribute("__idm_id__"));
c || (c = this.r << 10 | this.F++, b.setAttribute("__idm_id__", c));
this.c[c] = b;
return c
} catch (e) {}
};
m.h = function(b) {
var c;
try {
c = window.top.document.title
} catch (e) {}
if (c)
if (c = c.replace(/[ \t\r\n\u25B6]+/g, " ").trim(), b) this.a.postMessage([24, b, c]);
else return c
};
m.e = function(b) {
if (!this.l) {
var c = "\\b\\w+://(?:[%T]*(?::[%T]*)?#)?[%H.]+\\.[%H]+(?::\\d+)?(?:/(?:(?: +(?!\\w+:))?[%T/~;])*)?(?:\\?[%Q]*)?(?:#[%T]*)?".replace(/%\w/g,
function(b) {
return this[b]
}.bind({
"%H": "\\w\\-\u00a0-\ufeff",
"%T": "\\w\\-.+*()$!,%\u00a0-\ufeff",
"%Q": "^\\s\\[\\]{}()"
}));
this.l = new RegExp(c, "gi")
}
for (var e = []; c = this.l.exec(b);) e.push(c.shift());
return e
};
m.m = function(b, c, e) {
var f = [],
d = {},
n = "",
k = "",
p = !e,
q;
if (e && (q = b.getSelection(), !q || q.isCollapsed)) return f;
var r = b.getElementsByTagName("A");
if (r)
for (var h = 0; h < r.length; h++) {
var l = r[h];
if (l && (p || q.containsNode(l, !0))) {
var g = l.href;
g && !d[g] && c.test(g) && (d[g] = f.push([g, 2, l.innerText || l.title]));
e &&
d[g] && (n += l.innerText, n += "\n")
}
}
if (r = b.getElementsByTagName("AREA"))
for (h = 0; h < r.length; h++)(l = r[h]) && (p || q.containsNode(l, !0)) && (g = l.href) && !d[g] && c.test(g) && (d[g] = f.push([g, 2, l.alt]));
if (r = p && b.getElementsByTagName("IFRAME"))
for (h = 0; h < r.length; h++)(l = r[h]) && (p || q.containsNode(l, !0)) && (g = l.src) && !d[g] && c.test(g) && (d[g] = f.push([g, 4]));
if (h = e && q.toString())
for (l = this.e(h), n = this.e(n), h = 0; h < l.length; h++)(g = l[h]) && !d[g] && c.test(g) && 0 > n.indexOf(g) && (d[g] = f.push([g, 1]));
if (n = (p || !f.length) && b.getElementsByTagName("IMG"))
for (h =
0; h < n.length; h++)(l = n[h]) && (p || q.containsNode(l, !0)) && ((g = l.src) && !d[g] && c.test(g) && (d[g] = f.push([g, 3, "<<<=IDMTRANSMITIMGPREFIX=>>>" + l.alt])), p && l.onclick && (k += l.onclick, k += "\n"));
if (b = p && b.getElementsByTagName("SCRIPT")) {
for (h = 0; h < b.length; h++) k += b[h].innerText, k += "\n";
for (k = this.e(k); k.length;)(g = k.shift()) && !d[g] && c.test(g) && (d[g] = f.push([g, 5]))
}
return f
};
m.B = function(b, c) {
for (var e = this.m(document, b, c), f = document.getElementsByTagName("IFRAME"), d = Array.prototype.push, n = 0; n < f.length; n++) try {
var k =
f[n],
p = k.contentDocument;
p && !k.src && d.apply(e, this.m(p, b, c))
} catch (q) {}
return e
};
m.u = function(b) {
x[b.keyCode] && this.a.postMessage([31, b.keyCode, "keydown" == b.type])
};
m.L = function(b) {
this.s && this.a.postMessage([28]);
if (0 == b.button) {
var c = b.view.getSelection();
this.d = c && c.isCollapsed;
this.a.postMessage([32, b.button, !0])
}
};
m.M = function(b) {
if (0 == b.button && (this.i = b.clientX, this.j = b.clientY, this.a.postMessage([32, b.button, !1]), this.d)) {
this.d = !1;
var c = b.view.getSelection();
c && !c.isCollapsed && this.a.postMessage([26,
b.clientX, b.clientY, this.p()
])
}
};
m.K = function() {
this.d = !1;
this.a.postMessage([33])
};
m.O = function() {
this.a.postMessage([29])
};
m.N = function(b) {
b = b.target;
this.a.postMessage([30, b.innerWidth, b.innerHeight])
};
m.I = function(b) {
var c = b.target,
e = c.tagName;
0 <= C.indexOf(e) && b.url && (c = this.g(c), this.a.postMessage([25, c, e, b.url]))
};
m.J = function() {
this.t && this.f()
};
m.onMessage = function(b) {
switch (b[0]) {
case 11:
var c = b[2];
if (c) {
this.k = c;
try {
window.frameElement && window.frameElement.setAttribute("__idm_frm__", c)
} catch (e) {}
}
b[3] &&
this.o();
b[4] && this.f();
break;
case 17:
b[1] && this.o();
b[2] && this.f(!0);
break;
case 12:
var c = this.B(b[4] ? new RegExp(b[4], "i") : null, b[2]),
f = [27, b[1], this.k, c.length];
b[3] || (f[4] = c, f[5] = window.location.href, this.G && (f[6] = window.location.href, f[7] = document.title));
this.a.postMessage(f);
break;
case 13:
this.s = b[1];
break;
case 14:
this.h(b[1]);
break;
case 15:
this.C(b);
break;
case 16:
this.D(b)
}
};
m.b = function(b) {
var c = Array.prototype.slice.call(arguments);
c[2] = c[2].bind(this);
this.q.push(c);
b.addEventListener.apply(b,
c.slice(1))
};
m.v = function() {
for (var b; b = this.q.shift();) {
var c = b.shift();
c.removeEventListener.apply(c, b)
}
this.a = this.r = null;
window.a = !1
};
new t
};
It looks like one of your chrome extensions is throwing a javascript error. Please disable all of your chrome extensions and test. Especially disable Internet Download Manager if you have it installed.
Thanks Clayton Leis, I disabled the Internet Download Manager extension and error is gone. content script of idm extension was creating problem, Thanks again :).

Uncaught SyntaxError: Unexpected token

I have following script which is used to post comments. But when I try to submit the comment Google Chrome throws this error:
Uncaught SyntaxError: Unexpected token <
jax.processResponse
xmlhttp.onreadystatechange
I simply don't know what this error is all about.
function Jax() {
var loadingTimeout = 400;
var iframe;
this.loadingFunction = function () {};
this.doneLoadingFunction = function () {};
this.stringify = function (arg) {
var c, i, l, o, u, v;
switch (typeof arg) {
case "object":
if (arg) {
if (arg.constructor == Array) {
o = "";
for (i = 0; i < arg.length; ++i) {
v = this.stringify(arg[i]);
if (o && (v !== u)) {
o += ","
}
if (v !== u) {
o += v
}
}
return "[" + o + "]"
} else {
if (typeof arg.toString != "undefined") {
o = "";
for (i in arg) {
v = this.stringify(arg[i]);
if (v !== u) {
if (o) {
o += ","
}
o += this.stringify(i) + ":" + v
}
}
return "{" + o + "}"
} else {
return
}
}
}
return "";
case "unknown":
case "undefined":
case "function":
return u;
case "string":
arg = arg.replace(/"/g, '\\"');
l = arg.length;
o = '"';
for (i = 0; i < l; i += 1) {
c = arg.charAt(i);
if (c >= " ") {
if (c == "\\" || c == '"') {
o += "\\"
}
o += c
} else {
switch (c) {
case '"':
o += '\\"';
break;
case "\b":
o += "\\b";
break;
case "\f":
o += "\\f";
break;
case "\n":
o += "\\n";
break;
case "\r":
o += "\\r";
break;
case "\t":
o += "\\t";
break;
default:
c = c.charCodeAt();
o += "\\u00";
o += Math.floor(c / 16).toString(16);
o += (c % 16).toString(16)
}
}
}
return o + '"';
default:
return String(arg)
}
};
this.getRequestObject = function () {
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var msxmlhttp = new Array("Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP");
for (var i = 0; i < msxmlhttp.length; i++) {
try {
http_request = new ActiveXObject(msxmlhttp[i])
} catch (e) {
http_request = null
}
}
}
}
if (!http_request) {
alert("Unfortunatelly you browser doesn't support this feature.");
return false
}
return http_request
};
this.$ = function (sId) {
if (!sId) {
return null
}
var returnObj = document.getElementById(sId);
if (!returnObj && document.all) {
returnObj = document.all[sId]
}
return returnObj
};
this.addEvent = function (obj, type, fn) {
if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function () {
obj["e" + type + fn](window.event)
};
obj.attachEvent("on" + type, obj[type + fn])
} else {
obj.addEventListener(type, fn, false)
}
};
this.removeEvent = function (obj, type, fn) {
if (obj.detachEvent) {
obj.detachEvent("on" + type, obj[type + fn]);
obj[type + fn] = null
} else {
obj.removeEventListener(type, fn, false)
}
};
this.submitITask = function (comName, func, postData, responseFunc) {
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc, true);
this.loadingFunction();
if (!this.iframe) {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("id", "ajaxIframe");
this.iframe.setAttribute("height", 0);
this.iframe.setAttribute("width", 0);
this.iframe.setAttribute("border", 0);
this.iframe.style.visibility = "hidden";
document.body.appendChild(this.iframe);
this.iframe.src = xmlReq
} else {
this.iframe.src = xmlReq
}
};
this.extractIFrameBody = function (iFrameEl) {
var doc = null;
if (iFrameEl.contentDocument) {
doc = iFrameEl.contentDocument
} else {
if (iFrameEl.contentWindow) {
doc = iFrameEl.contentWindow.document
} else {
if (iFrameEl.document) {
doc = iFrameEl.document
} else {
alert("Error: could not find sumiFrame document");
return null
}
}
}
return doc.body
};
this.buildXmlReq = function (comName, func, postData, responseFunc, iframe) {
var xmlReq = "";
if (iframe) {
xmlReq += "?"
} else {
xmlReq += "&"
}
xmlReq += "option=" + comName;
xmlReq += "&no_html=1";
xmlReq += "&task=azrul_ajax";
xmlReq += "&func=" + func;
xmlReq += "&" + jax_token_var + "=1";
if (postData) {
xmlReq += "&" + postData
}
return xmlReq
};
this.submitTask = function (comName, func, postData, responseFunc) {
var xmlhttp = this.getRequestObject();
var targetUrl = jax_live_site;
xmlhttp.open("POST", targetUrl, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
jax.doneLoadingFunction();
jax.processResponse(xmlhttp.responseText)
} else {}
}
};
var id = 1;
var xmlReq = this.buildXmlReq(comName, func, postData, responseFunc);
this.loadingFunction();
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(xmlReq)
};
this.processIResponse = function () {
jax.doneLoadingFunction();
var resp = (this.extractIFrameBody(this.iframe).innerHTML);
resp = resp.replace(/</g, "<");
resp = resp.replace(/>/g, ">");
resp = resp.replace(/&/g, "&");
resp = resp.replace(/"/g, '"');
resp = resp.replace(/'/g, "'");
this.processResponse(resp)
};
this.BetterInnerHTML = function (o, p, q) {
function r(a) {
var b;
if (typeof DOMParser != "undefined") {
b = (new DOMParser()).parseFromString(a, "application/xml")
} else {
var c = ["MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"];
for (var i = 0; i < c.length && !b; i++) {
try {
b = new ActiveXObject(c[i]);
b.loadXML(a)
} catch (e) {}
}
}
return b
}
function s(a, b, c) {
a[b] = function () {
return eval(c)
}
}
function t(b, c, d) {
if (typeof d == "undefined") {
d = 1
}
if (d > 1) {
if (c.nodeType == 1) {
var e = document.createElement(c.nodeName);
var f = {};
for (var a = 0, g = c.attributes.length; a < g; a++) {
var h = c.attributes[a].name,
k = c.attributes[a].value,
l = (h.substr(0, 2) == "on");
if (l) {
f[h] = k
} else {
switch (h) {
case "class":
e.className = k;
break;
case "for":
e.htmlFor = k;
break;
default:
e.setAttribute(h, k)
}
}
}
b = b.appendChild(e);
for (l in f) {
s(b, l, f[l])
}
} else {
if (c.nodeType == 3) {
var m = (c.nodeValue ? c.nodeValue : "");
var n = m.replace(/^\s*|\s*$/g, "");
if (n.length < 7 || (n.indexOf("<!--") != 0 && n.indexOf("-->") != (n.length - 3))) {
b.appendChild(document.createTextNode(m))
}
}
}
}
for (var i = 0, j = c.childNodes.length; i < j; i++) {
t(b, c.childNodes[i], d + 1)
}
}
p = "<root>" + p + "</root>";
var u = r(p);
if (o && u) {
if (q != false) {
while (o.lastChild) {
o.removeChild(o.lastChild)
}
}
t(o, u.documentElement)
}
};
this.processResponse = function (responseTxt) {
var result = eval(responseTxt);
for (var i = 0; i < result.length; i++) {
var cmd = result[i][0];
var id = result[i][1];
var property = result[i][2];
var data = result[i][3];
var objElement = this.$(id);
switch (cmd) {
case "as":
if (objElement) {
eval("objElement." + property + "= data ; ")
}
break;
case "al":
if (data) {
alert(data)
}
break;
case "ce":
this.create(id, property, data);
break;
case "rm":
this.remove(id);
break;
case "cs":
var scr = id + "(";
if (this.isArray(data)) {
scr += "(data[0])";
for (var l = 1; l < data.length; l++) {
scr += ",(data[" + l + "])"
}
} else {
scr += "data"
}
scr += ");";
eval(scr);
break;
default:
alert("Unknow command: " + cmd)
}
}
};
this.isArray = function (obj) {
if (obj) {
return obj.constructor == Array
}
return false
};
this.buildCall = function (comName, sFunction) {};
this.icall = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
if (jax_site_type == "1.5") {
this.submitTask(comName, sFunction, arg)
} else {
this.submitITask(comName, sFunction, arg)
}
};
this.call = function (comName, sFunction) {
var arg = "";
if (arguments.length > 2) {
for (var i = 2; i < arguments.length; i++) {
var a = arguments[i];
if (this.isArray(a)) {
arg += "arg" + i + "=" + this.stringify(a) + "&"
} else {
if (typeof a == "string") {
a = a.replace(/"/g, """);
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
} else {
var t = new Array("_d_", encodeURIComponent(a));
arg += "arg" + i + "=" + this.stringify(t) + "&"
}
}
}
}
this.submitTask(comName, sFunction, arg)
};
this.create = function (sParentId, sTag, sId) {
var objParent = this.$(sParentId);
objElement = document.createElement(sTag);
objElement.setAttribute("id", sId);
if (objParent) {
objParent.appendChild(objElement)
}
};
this.remove = function (sId) {
objElement = this.$(sId);
if (objElement && objElement.parentNode && objElement.parentNode.removeChild) {
objElement.parentNode.removeChild(objElement)
}
};
this.getFormValues = function (frm) {
var objForm;
objForm = this.$(frm);
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from
}
}
return -1
}
}
var postData = new Array();
if (objForm && objForm.tagName == "FORM") {
var formElements = objForm.elements;
var assCheckbox = new Array();
var assCntIdx = 0;
var arrayHiddenValues = new Array();
var arrayHiddenCount = 0;
if (formElements.length > 0) {
for (var i = 0; i < formElements.length; i++) {
if (!formElements[i].name) {
continue
}
if (formElements[i].type && (formElements[i].type == "radio" || formElements[i].type == "checkbox") && formElements[i].checked == false) {
continue
}
var name = formElements[i].name;
if (name) {
if (formElements[i].type == "select-multiple") {
postData[i] = new Array();
for (var j = 0; j < formElements[i].length; j++) {
if (formElements[i].options[j].selected === true) {
var value = formElements[i].options[j].value;
postData[i][j] = new Array(name, encodeURIComponent(value))
}
}
} else {
if (formElements[i].type == "checkbox") {
if (assCheckbox.indexOf(formElements[i].name) == -1) {
assCheckbox[assCntIdx] = formElements[i].name;
assCntIdx++
}
} else {
if (formElements[i].type == "hidden") {
if (arrayHiddenValues.indexOf(formElements[i].name) == -1) {
arrayHiddenValues[arrayHiddenCount] = formElements[i].name;
arrayHiddenCount++
}
} else {
var value = formElements[i].value;
value = value.replace(/"/g, """);
postData[i] = new Array(name, encodeURIComponent(value))
}
}
}
}
}
}
if (arrayHiddenValues.length > 0) {
for (var i = 0; i < arrayHiddenValues.length; i++) {
var hiddenElement = document.getElementsByName(arrayHiddenValues[i]);
if (hiddenElement) {
if (hiddenElement.length > 1) {
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < hiddenElement.length; j++) {
var value = hiddenElement[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
} else {
var value = hiddenElement[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(arrayHiddenValues[i], encodeURIComponent(value))
}
}
}
}
if (assCheckbox.length > 0) {
for (var i = 0; i < assCheckbox.length; i++) {
var objCheckbox = document.getElementsByName(assCheckbox[i]);
if (objCheckbox) {
if (objCheckbox.length > 1) {
var tmpIdx = 0;
var curLen = postData.length;
postData[curLen] = new Array();
for (var j = 0; j < objCheckbox.length; j++) {
if (objCheckbox[j].checked) {
var value = objCheckbox[j].value;
value = value.replace(/"/g, """);
postData[curLen][j] = new Array(assCheckbox[i], encodeURIComponent(value));
tmpIdx++
}
}
} else {
if (objCheckbox[0].checked) {
var value = objCheckbox[0].value;
value = value.replace(/"/g, """);
postData[postData.length] = new Array(assCheckbox[i], encodeURIComponent(value))
}
}
}
}
}
}
return postData
}
}
function jax_iresponse() {
jax.processIResponse()
}
var jax = new Jax();
Please help me.
I'm not sure anyone should read obfuscated, minified code, but i found this:
**xmlhttp.onreadystatechange**=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
jax.doneLoadingFunction();
**jax.processResponse**(xmlhttp.responseText)}
else{}
}
};
Which returns a js error on line 1 :))
Are you allowed to use ** with variable names in js?
check if your bug is not here line 296
var result = eval(responseTxt);
What are you getting as a response? is it html, json?
Check also for notices in your backend script,
You can check this with the console/inspector in chrome (f12) , network tab.
It could be even be a debug output/notice/error from your backend script.
If you open it with firefox, i think firebug shows you a JSON tab if your response is in correct json format.

Categories

Resources