Related
in the home page the search bar doesn't work by entering a keyword it goes into a loop and we don't display the list of search results from the console we display these errors advice to solve the problem, below is the code where we find the error if it helps
we think this is the code related to the problem, we await feedback and suggestions to solve the problem
try {
r.send(i.hasContent && i.data || null)
} catch (e) {
if (o) throw e
}
}, abort: function() {
o && o()
}
}
}), S.ajaxPrefilter(function(e) {
e.crossDomain && (e.contents.script = !1)
}), S.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function(e) {
return S.globalEval(e), e
}
}
}), S.ajaxPrefilter("script", function(e) {
void 0 === e.cache && (e.cache = !1), e.crossDomain && (e.type = "GET")
}), S.ajaxTransport("script", function(n) {
var r, i;
if (n.crossDomain || n.scriptAttrs) return {
send: function(e, t) {
r = S("<script>").attr(n.scriptAttrs || {}).prop({
charset: n.scriptCharset,
src: n.url
}).on("load error", i = function(e) {
r.remove(), i = null, e && t("error" === e.type ? 404 : 200, e.type)
}), E.head.appendChild(r[0])
},
abort: function() {
i && i()
}
}
});
var Ut, Xt = [],
Vt = /(=)\?(?=&|$)|\?\?/;
S.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var e = Xt.pop() || S.expando + "_" + Ct.guid++;
return this[e] = !0, e
}
}), S.ajaxPrefilter("json jsonp", function(e, t, n) {
var r, i, o, a = !1 !== e.jsonp && (Vt.test(e.url) ? "url" : "string" == typeof e.data && 0 === (e.contentType || "").indexOf("application/x-www-form-urlencoded") && Vt.test(e.data) && "data");
if (a || "jsonp" === e.dataTypes[0]) return r = e.jsonpCallback = m(e.jsonpCallback) ? e.jsonpCallback() : e.jsonpCallback, a ? e[a] = e[a].replace(Vt, "$1" + r) : !1 !== e.jsonp && (e.url += (Et.test(e.url) ? "&" : "?") + e.jsonp + "=" + r), e.converters["script json"] = function() {
return o || S.error(r + " was not called"), o[0]
}, e.dataTypes[0] = "json", i = C[r], C[r] = function() {
o = arguments
}, n.always(function() {
void 0 === i ? S(C).removeProp(r) : C[r] = i, e[r] && (e.jsonpCallback = t.jsonpCallback, Xt.push(r)), o && m(i) && i(o[0]), o = i = void 0
}), "script"
}), v.createHTMLDocument = ((Ut = E.implementation.createHTMLDocument("").body).innerHTML = "<form></form><form></form>", 2 === Ut.childNodes.length), S.parseHTML = function(e, t, n) {
return "string" != typeof e ? [] : ("boolean" == typeof t && (n = t, t = !1), t || (v.createHTMLDocument ? ((r = (t = E.implementation.createHTMLDocument("")).createElement("base")).href = E.location.href, t.head.appendChild(r)) : t = E), o = !n && [], (i = N.exec(e)) ? [t.createElement(i[1])] : (i = xe([e], t, o), o && o.length && S(o).remove(), S.merge([], i.childNodes)));
var r, i, o
}, S.fn.load = function(e, t, n) {
var r, i, o, a = this,
s = e.indexOf(" ");
return -1 < s && (r = yt(e.slice(s)), e = e.slice(0, s)), m(t) ? (n = t, t = void 0) : t && "object" == typeof t && (i = "POST"), 0 < a.length && S.ajax({
url: e,
type: i || "GET",
dataType: "html",
data: t
}).done(function(e) {
o = arguments, a.html(r ? S("<div>").append(S.parseHTML(e)).find(r) : e)
}).always(n && function(e, t) {
a.each(function() {
n.apply(this, o || [e.responseText, t, e])
})
}), this
}, S.expr.pseudos.animated = function(t) {
return S.grep(S.timers, function(e) {
return t === e.elem
}).length
}, S.offset = {
setOffset: function(e, t, n) {
var r, i, o, a, s, u, l = S.css(e, "position"),
c = S(e),
f = {};
"static" === l && (e.style.position = "relative"), s = c.offset(), o = S.css(e, "top"), u = S.css(e, "left"), ("absolute" === l || "fixed" === l) && -1 < (o + u).indexOf("auto") ? (a = (r = c.position()).top, i = r.left) : (a = parseFloat(o) || 0, i = parseFloat(u) || 0), m(t) && (t = t.call(e, n, S.extend({}, s))), null != t.top && (f.top = t.top - s.top + a), null != t.left && (f.left = t.left - s.left + i), "using" in t ? t.using.call(e, f) : c.css(f)
}
}, S.fn.extend({
offset: function(t) {
if (arguments.length) return void 0 === t ? this : this.each(function(e) {
S.offset.setOffset(this, t, e)
});
var e, n, r = this[0];
return r ? r.getClientRects().length ? (e = r.getBoundingClientRect(), n = r.ownerDocument.defaultView, {
top: e.top + n.pageYOffset,
left: e.left + n.pageXOffset
}) : {
top: 0,
left: 0
} : void 0
},
position: function() {
if (this[0]) {
var e, t, n, r = this[0],
i = {
top: 0,
left: 0
};
if ("fixed" === S.css(r, "position")) t = r.getBoundingClientRect();
else {
t = this.offset(), n = r.ownerDocument, e = r.offsetParent || n.documentElement;
while (e && (e === n.body || e === n.documentElement) && "static" === S.css(e, "position")) e = e.parentNode;
e && e !== r && 1 === e.nodeType && ((i = S(e).offset()).top += S.css(e, "borderTopWidth", !0), i.left += S.css(e, "borderLeftWidth", !0))
}
return {
top: t.top - i.top - S.css(r, "marginTop", !0),
left: t.left - i.left - S.css(r, "marginLeft", !0)
}
}
},
offsetParent: function() {
return this.map(function() {
var e = this.offsetParent;
while (e && "static" === S.css(e, "position")) e = e.offsetParent;
return e || re
})
}
}), S.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(t, i) {
var o = "pageYOffset" === i;
S.fn[t] = function(e) {
return B(this, function(e, t, n) {
var r;
if (x(e) ? r = e : 9 === e.nodeType && (r = e.defaultView), void 0 === n) return r ? r[i] : e[t];
r ? r.scrollTo(o ? r.pageXOffset : n, o ? n : r.pageYOffset) : e[t] = n
}, t, e, arguments.length)
}
}), S.each(["top", "left"], function(e, n) {
S.cssHooks[n] = _e(v.pixelPosition, function(e, t) {
if (t) return t = Be(e, n), Pe.test(t) ? S(e).position()[n] + "px" : t
})
}), S.each({
Height: "height",
Width: "width"
}, function(a, s) {
S.each({
padding: "inner" + a,
content: s,
"": "outer" + a
}, function(r, o) {
S.fn[o] = function(e, t) {
var n = arguments.length && (r || "boolean" != typeof e),
i = r || (!0 === e || !0 === t ? "margin" : "border");
return B(this, function(e, t, n) {
var r;
return x(e) ? 0 === o.indexOf("outer") ? e["inner" + a] : e.document.documentElement["client" + a] : 9 === e.nodeType ? (r = e.documentElement, Math.max(e.body["scroll" + a], r["scroll" + a], e.body["offset" + a], r["offset" + a], r["client" + a])) : void 0 === n ? S.css(e, t, i) : S.style(e, t, n, i)
}, s, n ? e : void 0, n)
}
})
}), S.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(e, t) {
S.fn[t] = function(e) {
return this.on(t, e)
}
}), S.fn.extend({
bind: function(e, t, n) {
return this.on(e, null, t, n)
},
unbind: function(e, t) {
return this.off(e, null, t)
},
delegate: function(e, t, n, r) {
return this.on(t, e, n, r)
},
undelegate: function(e, t, n) {
return 1 === arguments.length ? this.off(e, "**") : this.off(t, e || "**", n)
},
hover: function(e, t) {
return this.mouseenter(e).mouseleave(t || e)
}
}), S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "), function(e, n) {
S.fn[n] = function(e, t) {
return 0 < arguments.length ? this.on(n, null, e, t) : this.trigger(n)
}
});
var Gt = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;
S.proxy = function(e, t) {
var n, r, i;
if ("string" == typeof t && (n = e[t], t = e, e = n), m(e)) return r = s.call(arguments, 2), (i = function() {
return e.apply(t || this, r.concat(s.call(arguments)))
}).guid = e.guid = e.guid || S.guid++, i
}, S.holdReady = function(e) {
e ? S.readyWait++ : S.ready(!0)
}, S.isArray = Array.isArray, S.parseJSON = JSON.parse, S.nodeName = A, S.isFunction = m, S.isWindow = x, S.camelCase = X, S.type = w, S.now = Date.now, S.isNumeric = function(e) {
var t = S.type(e);
return ("number" === t || "string" === t) && !isNaN(e - parseFloat(e))
}, S.trim = function(e) {
return null == e ? "" : (e + "").replace(Gt, "$1")
}, "function" == typeof define && define.amd && define("jquery", [], function() {
return S
});
var Yt = C.jQuery,
Qt = C.$;
return S.noConflict = function(e) {
return C.$ === S && (C.$ = Qt), e && C.jQuery === S && (C.jQuery = Yt), S
}, "undefined" == typeof e && (C.jQuery = C.$ = S), S
});
jQuery.noConflict();
I am trying to create a navigation menu of the mobile view of my website with jQuery, but when I call it inside the className of my reactjs application, it does not work. I have placed the jQuery file inside my public folder of the react application and called it from the index.html file
Here is the sample jQuery code from the public folder:
! function($) {
"use strict";
$.fn.meanmenu = function(e) {
var n = {
meanMenuTarget: jQuery(this),
meanMenuContainer: ".mobile-nav",
meanMenuClose: "X",
meanMenuCloseSize: "18px",
meanMenuOpen: "<span /><span /><span />",
meanRevealPosition: "right",
meanRevealPositionDistance: "0",
meanRevealColour: "",
meanScreenWidth: "480",
meanNavPush: "",
meanShowChildren: !0,
meanExpandableChildren: !0,
meanExpand: "+",
meanContract: "-",
meanRemoveAttrs: !1,
onePage: !1,
meanDisplay: "block",
removeElements: ""
};
e = $.extend(n, e);
var a = window.innerWidth || document.documentElement.clientWidth;
return this.each(function() {
var n = e.meanMenuTarget,
t = e.meanMenuContainer,
r = e.meanMenuClose,
i = e.meanMenuCloseSize,
s = e.meanMenuOpen,
u = e.meanRevealPosition,
m = e.meanRevealPositionDistance,
l = e.meanRevealColour,
o = e.meanScreenWidth,
c = e.meanNavPush,
v = ".meanmenu-reveal",
h = e.meanShowChildren,
d = e.meanExpandableChildren,
y = e.meanExpand,
j = e.meanContract,
Q = e.meanRemoveAttrs,
f = e.onePage,
g = e.meanDisplay,
p = e.removeElements,
C = !1;
(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/Blackberry/i) || navigator.userAgent.match(/Windows Phone/i)) && (C = !0), (navigator.userAgent.match(/MSIE 8/i) || navigator.userAgent.match(/MSIE 7/i)) && jQuery("html").css("overflow-y", "scroll");
var w = "",
x = function() {
if ("center" === u) {
var e = window.innerWidth || document.documentElement.clientWidth,
n = e / 2 - 22 + "px";
w = "left:" + n + ";right:auto;", C ? jQuery(".meanmenu-reveal").animate({
left: n
}) : jQuery(".meanmenu-reveal").css("left", n)
}
},
A = !1,
E = !1;
"right" === u && (w = "right:" + m + ";left:auto;"), "left" === u && (w = "left:" + m + ";right:auto;"), x();
var M = "",
P = function() {
M.html(jQuery(M).is(".meanmenu-reveal.meanclose") ? r : s)
},
W = function() {
jQuery(".mean-bar,.mean-push").remove(), jQuery(t).removeClass("mean-container"), jQuery(n).css("display", g), A = !1, E = !1, jQuery(p).removeClass("mean-remove")
},
b = function() {
var e = "background:" + l + ";color:" + l + ";" + w;
if (o >= a) {
jQuery(p).addClass("mean-remove"), E = !0, jQuery(t).addClass("mean-container"), jQuery(".mean-container").prepend('<div class="mean-bar">Show Navigation<nav class="mean-nav"></nav></div>');
var r = jQuery(n).html();
jQuery(".mean-nav").html(r), Q && jQuery("nav.mean-nav ul, nav.mean-nav ul *").each(function() {
jQuery(this).is(".mean-remove") ? jQuery(this).attr("class", "mean-remove") : jQuery(this).removeAttr("class"), jQuery(this).removeAttr("id")
}), jQuery(n).before('<div class="mean-push" />'), jQuery(".mean-push").css("margin-top", c), jQuery(n).hide(), jQuery(".meanmenu-reveal").show(), jQuery(v).html(s), M = jQuery(v), jQuery(".mean-nav ul").hide(), h ? d ? (jQuery(".mean-nav ul ul").each(function() {
jQuery(this).children().length && jQuery(this, "li:first").parent().append('<a class="mean-expand" href="#" style="font-size: ' + i + '">' + y + "</a>")
}), jQuery(".mean-expand").on("click", function(e) {
e.preventDefault(), jQuery(this).hasClass("mean-clicked") ? (jQuery(this).text(y), jQuery(this).prev("ul").slideUp(300, function() {})) : (jQuery(this).text(j), jQuery(this).prev("ul").slideDown(300, function() {})), jQuery(this).toggleClass("mean-clicked")
})) : jQuery(".mean-nav ul ul").show() : jQuery(".mean-nav ul ul").hide(), jQuery(".mean-nav ul li").last().addClass("mean-last"), M.removeClass("meanclose"), jQuery(M).click(function(e) {
e.preventDefault(), A === !1 ? (M.css("text-align", "center"), M.css("text-indent", "0"), M.css("font-size", i), jQuery(".mean-nav ul:first").slideDown(), A = !0) : (jQuery(".mean-nav ul:first").slideUp(), A = !1), M.toggleClass("meanclose"), P(), jQuery(p).addClass("mean-remove")
}), f && jQuery(".mean-nav ul > li > a:first-child").on("click", function() {
jQuery(".mean-nav ul:first").slideUp(), A = !1, jQuery(M).toggleClass("meanclose").html(s)
})
} else W()
};
C || jQuery(window).resize(function() {
a = window.innerWidth || document.documentElement.clientWidth, a > o, W(), o >= a ? (b(), x()) : W()
}), jQuery(window).resize(function() {
a = window.innerWidth || document.documentElement.clientWidth, C ? (x(), o >= a ? E === !1 && b() : W()) : (W(), o >= a && (b(), x()))
}), b()
})
}
}(jQuery);
And this is how I am using it in the reactJs Navbar.js:
<div className="mobile-nav">
<a href="index.html" className="logo">
<img src="assets/img/logo.png" alt="Logo">
</a>
</div>
useEffect more detail see https://reactjs.org/docs/hooks-reference.html#useeffect
function Menu(){
React.useEffect(()=> {
$('.mobile-nav').meanmenu()
}, [])
return (
<div className="mobile-nav">
<a href="index.html" className="logo">
<img src="assets/img/logo.png" alt="Logo">
</a>
</div>
)
}
I want to add factorial (n!) calculation to Calculated Fields Form WordPress plugin. I found out that module_public.js (in this direction: wp-content\plugins\calculated-fields-form\js\modules\01_mathematical_logical\public) contains the code for math operations and I added these codes, but they did not work (I can make a button for factorial by adding code to module_admin.js and the button works but I can't get the result).
Can anyone help me?
My codes that I added to line 209 in module_public.js:
if(window.FAC == undefined)
{
window.FAC = window.fac = function ()
{
var ans=1;
for (var i = 2; i <= FAC; i++)
ans = ans * i;
return ans;
};
} // End if window.FAC
original code of module_public.js:
fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery[ 'fbuilder' ] = f
builderjQuery[ 'fbuilder' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'mo
dules' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ] = {
'prefix' : '',
'callback' : function()
{
if(Number.prototype.LENGTH == undefined)
{
// Only LENGTH in uppercase to prevent a conflict with Lottie
Number.prototype.LENGTH = function(){return this.valueOf().toString().length;};
}
function ROUNDx(operation, num, y)
{
if(y && y != 0)
{
var r = operation(num/y)*y, p = (new String(y)).split('.');
if(p.length == 2) r = PREC(r,p[1].length);
return r;
}
else
{
return operation(num);
}
};
if(window.ROUND == undefined)
{
window.ROUND = window.round = function(num, y)
{
if(y) return ROUNDx(Math.round, num, y);
return ROUNDx(Math.round, num);
}
}
if(window.FLOOR == undefined)
{
window.FLOOR = window.floor = function(num, y)
{
if(y) return ROUNDx(Math.floor, num, y);
return ROUNDx(Math.floor, num);
}
}
if(window.CEIL == undefined)
{
window.CEIL = window.ceil = function(num, y)
{
if(y) return ROUNDx(Math.ceil, num, y);
return ROUNDx(Math.ceil, num);
}
}
if(window.PREC == undefined)
{
window.PREC = window.prec = function (num, pr)
{
if('undefined' == typeof pr) pr = 0;
if(/^\d+$/.test(pr) && $.isNumeric(num))
{
var f = POW(10,pr);
num = ROUND(num*f)/f;
return num.toFixed(pr);
}
return num;
};
} // End if window.PREC
if(window.CDATE == undefined)
{
window.CDATE = window.cdate = function ( num, format )
{
format = ( typeof format != 'undefined' ) ? format : ( ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'dd/mm/yyyy' );
if(isFinite(num*1))
{
num = Math.round(num*86400000);
var date = new Date(num),
d = date.getDate(),
m = date.getMonth()+1,
y = date.getFullYear(),
h = date.getHours(),
i = date.getMinutes(),
s = date.getSeconds(),
a = '';
m = (m < 10) ? '0'+m : m;
d = (d < 10) ? '0'+d : d;
if( /a/.test( format ) )
{
a = ( h >= 12 ) ? 'pm' : 'am';
h = h % 12;
h = ( h == 0 ) ? 12: h;
}
h = (h < 10) ? '0'+h : h;
i = (i < 10) ? '0'+i : i;
s = (s < 10) ? '0'+s : s;
return format.replace( /y+/i, y)
.replace( /m+/i, m)
.replace( /d+/i, d)
.replace( /h+/i, h)
.replace( /i+/i, i)
.replace( /s+/i, s)
.replace( /a+/i, a);
}
return num;
};
} // End if window.CDATE
if(window.SUM == undefined)
{
window.SUM = window.sum = function ()
{
var r = 0, t;
for(var i in arguments)
{
if(Array.isArray(arguments[i])) r += SUM.apply(this,arguments[i]);
else
{
t = arguments[i]*1;
if(!isNaN(t)) r += t;
}
}
return r;
};
} // End if window.SUM
if(window.CONCATENATE == undefined)
{
window.CONCATENATE = window.concatenate = function ()
{
var r = '';
for(var i in arguments)
if(Array.isArray(arguments[i])) r += CONCATENATE.apply(this,arguments[i]);
else r += (new String(arguments[i]));
return r;
};
} // End if window.CONCATENATE
if(window.AVERAGE == undefined)
{
window.AVERAGE = window.average = function ()
{
return SUM.apply(this,arguments)/arguments.length;
};
} // End if window.AVERAGE
if(window.GCD == undefined)
{
window.GCD = window.gcd = function( a, b)
{
if ( ! b) return a;
return GCD(b, a % b);
};
} // End if window.GCD
if(window.LCM == undefined)
{
window.LCM = window.lcm = function( a, b)
{
return (!a || !b) ? 0 : ABS((a * b) / GCD(a, b));
};
} // End if window.LCM
if(window.LOGAB == undefined)
{
window.LOGAB = window.logab = function( a, b)
{
return LOG(a)/LOG(b);
};
} // End if window.LOGAB
var math_prop = ["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "asin", "abs", "exp", "atan2", "atanh", "random", "acos", "atan", "sin"];
for(var i = 0, h = math_prop.length; i < h; i++)
{
if( !window[ math_prop[ i ] ] )
{
window[ math_prop[ i ] ] = window[ math_prop[ i ].toUpperCase() ] = Math[ math_prop[ i ] ];
}
}
if(window.MIN == undefined)
{
window.MIN = window.min = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.min.apply(this, l);
};
} // End if window.MIN
if(window.MAX == undefined)
{
window.MAX = window.max = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.max.apply(this, l);
};
} // End if window.MAX
if(window.RADIANS == undefined)
{
window.RADIANS = window.radians = function(a){ return a*PI/180;};
}
if(window.DEGREES == undefined)
{
window.DEGREES = window.degrees = function(a){ return a*180/PI;};
}
fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ][ 'prefix' ], CF_LOGICAL );
},
'validator' : function( v )
{
return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' );
}
};
try to paste the code below!
fbuilderjQuery = ( typeof fbuilderjQuery != 'undefined' ) ? fbuilderjQuery : jQuery;
fbuilderjQuery[ 'fbuilder' ] = f
builderjQuery[ 'fbuilder' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ] = fbuilderjQuery[ 'fbuilder' ][ 'mo
dules' ] || {};
fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ] = {
'prefix' : '',
'callback' : function()
{
if(Number.prototype.LENGTH == undefined)
{
// Only LENGTH in uppercase to prevent a conflict with Lottie
Number.prototype.LENGTH = function(){return this.valueOf().toString().length;};
}
function ROUNDx(operation, num, y)
{
if(y && y != 0)
{
var r = operation(num/y)*y, p = (new String(y)).split('.');
if(p.length == 2) r = PREC(r,p[1].length);
return r;
}
else
{
return operation(num);
}
};
if(window.ROUND == undefined)
{
window.ROUND = window.round = function(num, y)
{
if(y) return ROUNDx(Math.round, num, y);
return ROUNDx(Math.round, num);
}
}
if(window.FLOOR == undefined)
{
window.FLOOR = window.floor = function(num, y)
{
if(y) return ROUNDx(Math.floor, num, y);
return ROUNDx(Math.floor, num);
}
}
if(window.CEIL == undefined)
{
window.CEIL = window.ceil = function(num, y)
{
if(y) return ROUNDx(Math.ceil, num, y);
return ROUNDx(Math.ceil, num);
}
}
if(window.PREC == undefined)
{
window.PREC = window.prec = function (num, pr)
{
if('undefined' == typeof pr) pr = 0;
if(/^\d+$/.test(pr) && $.isNumeric(num))
{
var f = POW(10,pr);
num = ROUND(num*f)/f;
return num.toFixed(pr);
}
return num;
};
} // End if window.PREC
if(window.CDATE == undefined)
{
window.CDATE = window.cdate = function ( num, format )
{
format = ( typeof format != 'undefined' ) ? format : ( ( typeof window.DATETIMEFORMAT != 'undefined' ) ? window.DATETIMEFORMAT : 'dd/mm/yyyy' );
if(isFinite(num*1))
{
num = Math.round(num*86400000);
var date = new Date(num),
d = date.getDate(),
m = date.getMonth()+1,
y = date.getFullYear(),
h = date.getHours(),
i = date.getMinutes(),
s = date.getSeconds(),
a = '';
m = (m < 10) ? '0'+m : m;
d = (d < 10) ? '0'+d : d;
if( /a/.test( format ) )
{
a = ( h >= 12 ) ? 'pm' : 'am';
h = h % 12;
h = ( h == 0 ) ? 12: h;
}
h = (h < 10) ? '0'+h : h;
i = (i < 10) ? '0'+i : i;
s = (s < 10) ? '0'+s : s;
return format.replace( /y+/i, y)
.replace( /m+/i, m)
.replace( /d+/i, d)
.replace( /h+/i, h)
.replace( /i+/i, i)
.replace( /s+/i, s)
.replace( /a+/i, a);
}
return num;
};
} // End if window.CDATE
if(window.SUM == undefined)
{
window.SUM = window.sum = function ()
{
var r = 0, t;
for(var i in arguments)
{
if(Array.isArray(arguments[i])) r += SUM.apply(this,arguments[i]);
else
{
t = arguments[i]*1;
if(!isNaN(t)) r += t;
}
}
return r;
};
} // End if window.SUM
if(window.CONCATENATE == undefined)
{
window.CONCATENATE = window.concatenate = function ()
{
var r = '';
for(var i in arguments)
if(Array.isArray(arguments[i])) r += CONCATENATE.apply(this,arguments[i]);
else r += (new String(arguments[i]));
return r;
};
} // End if window.CONCATENATE
if(window.AVERAGE == undefined)
{
window.AVERAGE = window.average = function ()
{
return SUM.apply(this,arguments)/arguments.length;
};
} // End if window.AVERAGE
if(window.GCD == undefined)
{
window.GCD = window.gcd = function( a, b)
{
if ( ! b) return a;
return GCD(b, a % b);
};
} // End if window.GCD
if(window.LCM == undefined)
{
window.LCM = window.lcm = function( a, b)
{
return (!a || !b) ? 0 : ABS((a * b) / GCD(a, b));
};
} // End if window.LCM
if(window.LOGAB == undefined)
{
window.LOGAB = window.logab = function( a, b)
{
return LOG(a)/LOG(b);
};
} // End if window.LOGAB
var math_prop = ["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "LN2", "cos", "pow", "log", "tan", "sqrt", "asin", "abs", "exp", "atan2", "atanh", "random", "acos", "atan", "sin"];
for(var i = 0, h = math_prop.length; i < h; i++)
{
if( !window[ math_prop[ i ] ] )
{
window[ math_prop[ i ] ] = window[ math_prop[ i ].toUpperCase() ] = Math[ math_prop[ i ] ];
}
}
if(window.MIN == undefined)
{
window.MIN = window.min = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.min.apply(this, l);
};
} // End if window.MIN
if(window.MAX == undefined)
{
window.MAX = window.max = function ()
{
var l = [];
for(var i in arguments)
var l = l.concat(arguments[i]);
return Math.max.apply(this, l);
};
} // End if window.MAX
if(window.FAC == undefined)
{
window.FAC = window.fac = function (num)
{
let sm=num;
if(num == 0)
return 1;
else{
for(let i=num-1; i>=1; i--){
sm *= (num-i);
console.log(sm);
}
return sm;
}
if(window.RADIANS == undefined)
{
window.RADIANS = window.radians = function(a){ return a*PI/180;};
}
if(window.DEGREES == undefined)
{
window.DEGREES = window.degrees = function(a){ return a*180/PI;};
}
fbuilderjQuery[ 'fbuilder' ][ 'extend_window' ]( fbuilderjQuery[ 'fbuilder' ][ 'modules' ][ 'default' ][ 'prefix' ], CF_LOGICAL );
},
'validator' : function( v )
{
return ( typeof v == 'number' ) ? isFinite( v ) : ( typeof v != 'undefined' );
}
};
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>
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 :).