Complex Javascript for performing a basic job - javascript

I came across a website that was using a very strange piece of code with a lot of variables and recursive functions just to forward the user to the main website. The code was obfuscated. After deobfuscation, it is as follows. Note that the go() function is executed upon click of a button named 'Enter Site':
(function (paetynn, jaquez) {
var lyons = quetzali, payzli = paetynn();
while (!![]) {
try {
var kyona = parseInt(lyons(295)) / 1 + -parseInt(lyons(300)) / 2 + parseInt(lyons(299)) / 3 + -parseInt(lyons(301)) / 4 * (parseInt(lyons(304)) / 5) + -parseInt(lyons(294)) / 6 * (parseInt(lyons(298)) / 7) + parseInt(lyons(297)) / 8 * (-parseInt(lyons(303)) / 9) + parseInt(lyons(305)) / 10;
if (kyona === jaquez) break; else payzli.push(payzli.shift());
} catch (zulekha) {
payzli.push(payzli.shift());
}
}
}(niree, 850584));
function quetzali(winston, ikeshia) {
var hongan = niree();
return quetzali = function (khole, kysin) {
khole = khole - 294;
var zebulan = hongan[khole];
return zebulan;
}, quetzali(winston, ikeshia);
}
function go() {
var amey = quetzali, gracelee = amey(296);
document[amey(302)] = gracelee, window.location = "/";
}
function niree() {
var saana = ["604264sauqJi", "10214183nDqKAH", "2078325AmAiPo", "1206860TDYYcJ", "4VhIfuJ", "cookie", "45pazGrL", "380390DQkmbn", "12476230senONL", "6bRFHSG", "1426528LpTiXE", "session_keys=mycheck;"];
niree = function () {
return saana;
};
return niree();
}
I don't fully understand what the code does. Could some JS expert clarify on the piece?
Seems like the code is manipulating window.location.
Also it was used inside a script tag inside the head tag of the page.

This code sets cookie session_keys=mycheck; and then redirects to /. The rest of code make permutation in the array of strings saana so analizyng code would be more difficult.

Related

How to call JS-Functions only on HTML pages where they are being used and not on all of them?

I am creating a demo-website for a fictional company.
The most of it is written in Javascript but I have a problem that all my functions are getting called on every HTML-page, even if they are not getting used.
Example: I have a Contact page where only one function should be called, but right now all functions are being called. Those for my Booking page and so on.
I am trying to use window.addEventListener together with window.location.pathname without result.
function start() {
// variable for pathname. split in to substrings by '/'
var pathArray = window.location.pathname.split('/');
// check the last substring of the array for determening which script to
run
if(pathArray[pathArray.length-1] == "contact.html")
{
browserDetect();
}
else if(pathArray[pathArray.length-1] == "ourfleet.html")
{
showFirstFleetImg();
showFleetImg();
}
else if(pathArray[pathArray.length-1] == "employees.html")
{
showFirstStaffImg();
showStaffImg();
}
}
window.addEventListener("load", start, false);
One of the functions
function showFleetImg(arrayno) {
var fleethtml = "";
var caption = document.getElementById("planename");
for(var i = 0; i < fleetarray.length; i++) {
fleethtml = fleethtml + "<a href = '#' onclick = 'showFleetImg(" + i +
"); return false; '><img src='" + fleetarray[i] + "' /></a>";
}
fleetimage.src = fleetarray[arrayno];
caption.innerHTML = planename[arrayno];
document.getElementById("fleetthumbs").innerHTML= fleethtml;
}
function showFirstFleetImg(imgnum) {
showFleetImg(0);
}
window.addEventListener("load", showFirstFleetImg, false);
What more do I add, or how do I structure this right so function X is only called in HTML file Y?
It looks like you are looking for something like ES Modules. There is a lot of information here http://exploringjs.com/es6/ch_modules.html, but the gist is they encapsulation javascript code so that functions aren't executed right away.
If you rewrite your javascript file to something like
// foo.js
export function showFleetImg(arrayno) {
var fleethtml = "";
var caption = document.getElementById("planename");
for(var i = 0; i < fleetarray.length; i++) {
fleethtml = fleethtml + "<a href = '#' onclick = 'showFleetImg(" + i +
"); return false; '><img src='" + fleetarray[i] + "' /></a>";
}
fleetimage.src = fleetarray[arrayno];
caption.innerHTML = planename[arrayno];
document.getElementById("fleetthumbs").innerHTML= fleethtml;
}
export function showFirstFleetImg(imgnum) {
showFleetImg(0);
}
and then your other js file will look like
import {showFleetImg, showFirstFleetImg} from './foo.js'
function start() {
// variable for pathname. split in to substrings by '/'
var pathArray = window.location.pathname.split('/');
// check the last substring of the array for determening which script to
run
if(pathArray[pathArray.length-1] == "contact.html")
{
browserDetect();
}
else if(pathArray[pathArray.length-1] == "ourfleet.html")
{
showFirstFleetImg();
showFleetImg();
}
else if(pathArray[pathArray.length-1] == "employees.html")
{
showFirstStaffImg();
showStaffImg();
}
}
There is nothing in the code you've posted to suggest each function should first every time.
However, there are many better ways to do what you're trying to do.
Use separate JS files and call into each page only those that need to be executed
If you prefer to use one JS file like currently, don't conditionalise based on pathname; what if your filename changes? You'd have to update your JS each time.
As regards the latter point, it would make more sense to act on the presence (or lack thereof) of a data attribute on the body identifying which page is currently showing.
HTML
<body data-page='contact'>
JS
switch (document.body.getAttribute('data-page')) {
case 'contact': /* do something */ break;
case 'fleet': /* do something else */ break;
//etc...
}
Note also the use of switch() rather than duplicative if/else if statements.
[Edit - or have a look at Modules as per #user1816294's answer]

Getting Compile error in Microsoft JScript (expected)

I tested a code with my friend and the code worked and now I wanted to test this again and got a Compile error in Microsoft JScript
Everything worked before
var iTest = 0;
if (iTest) {
let sText = "This is a template string which can contain variables like ${iTest}";
console.log(sText);
} else if (!iTest) {
let fnc = (iRadius, iPi = 3.14) => {
console.log("The area of the circle with the radius ${iRadius}cm is ${Math.round(iPi * iRadius * iRadius)}cm²");
}
fnc(3.14);
} else {
/* This is never going to be called since else if is already handling the only option besides the if */
}
var fnc = (iAlpha, iBravo, cb) => {
cb(iAlpha + iBravo);
}
fnc(84,255,(iResult) => {
console.log(iResult);
});
Template literals and arrow functions are not available in JScript. The latest version of JScript is based on ES5, and those two features are only available in ES2015. And console is not available in JScript if you are using the Windows Script Host; instead, use WScript.Echo().
var iTest = 0;
if (iTest) {
var sText = "This is a template string which can contain variables like " + iTest;
WScript.Echo(sText);
} else {
var fnc = function(iRadius, iPi) {
iPi = 3.14;
WScript.Echo("The area of the circle with the radius " + iRadius + "cm is " + Math.round(iPi * iRadius * iRadius) + "cm²");
}
fnc(3.14);
}
var fnc = function(iAlpha, iBravo, cb) {
cb(iAlpha + iBravo);
}
fnc(84, 255, function(iResult) {
WScript.Echo(iResult);
});
It would also be nice if you could provide more information about the particular error you are getting. This should fix it, but it would make it easier for us to help if we know exactly what the problem is.

How to define "interface" in js

Good day.
My question is quite dumb, I guess, but I'm not familiar enough with the termins, to ask it properly (and to get an answer from Google).
So - please help...
Shortly - I'm trying to create some major class, which will be insanitated by instances, which will describe some methods, and some fields.
Major logick will be implemented in parent class.
So, lets say I have a parent
function CRUD_Grid_model(){
//Settings part
this.GridElement = "" ;
this.editModeFlagElement = "" ;
this.newRowElement = "";
//Save logicks all lies here.
this.commit = function (){
alert("PLEASE REDEFINE COMMIT FUNCTION IN YOUR CODE");
}
;
//Settings part
//Some more code.
}
And a way I'll use it
//Das modell
var JobberCRUD = new CRUD_Grid_model();
JobberCRUD.GridElement = $('#jobbers_dg');
JobberCRUD.editModeFlagElement = $('#jobbers_tb_edit');
JobberCRUD.newRowElement = {jobb_name:'Enter new unique name',jobb_status:'Y'};
JobberCRUD.commit = function (){
if (this.endEditing()){
var addrows = this.GridElement.datagrid('getChanges','inserted');
var remrows = this.GridElement.datagrid('getChanges','deleted');
var updrows = this.GridElement.datagrid('getChanges','updated');
console.log(addrows);
console.log(remrows);
console.log(updrows);
//Send changes?
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
//Commit changes at local level
this.GridElement.datagrid('acceptChanges');
}
};
And, what I'd like to do, is smoething like this
I want a parent.commit function to allow me to do this in child
JobberCRUD.commit = function (apdrows,updrows,remrows){
//Send changes?
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
};
So, I have no ideas what shoudl I do to achieve that. Please advice me with some tags, what it is at least :)
Thanks in advance.
There is not exactly what you need in JavaScript, but I would tend to use this pattern :
function CRUD_Grid_model() {
...
this.onCommit = null;
this.commit = function (){
if (this.endEditing()){
var addrows = this.GridElement.datagrid('getChanges','inserted');
var remrows = this.GridElement.datagrid('getChanges','deleted');
var updrows = this.GridElement.datagrid('getChanges','updated');
if(this.onCommit != null) this.onCommit(addrows,updrows,remrows);
this.GridElement.datagrid('acceptChanges');
}
}
...
}
var JobberCRUD = new CRUD_Grid_model();
JobberCRUD.onCommit = function(apdrows,updrows,remrows) {
alert("Got total of " +addrows.length + remrows.length + updrows.length + " rows changed.");
};
JobberCRUD.GridElement = ...
Javascript doesn't have a built in notion of interfaces. A javascript object effectively "implements an interface" by having all the needed methods defined, but there's no language "interface" construct
You could use "extends" like so:
Object.prototype.extends = function(clazz) {
var o = new clazz();
for (var f in o) {
if(f === "extends") {
continue;
}
this[f] = o[f];
}
this.super = o;
}
Now could type something like this:
var JobberCRUD = function() {
this.extends(CRUD_Grid_model);
var privateFunction = function() {
//...
}
// You probably don't want to do that,
// but you could override
this.commit = function() {
//...
}
// ...
}
Hope, that helps.
Edit: forgot, that you may call super.commit() then.
You can not have something similar like C# or Java interface or even class with Javascript.
Javascript is just a dynamic scripting language.

showModalDialog alternative?

I'm managing an old site that's riddled with popup windows. They're quite annoying because they keep getting lost behind the main window. I'm slowly moving them over to over to a modern 'lightbox' but it's a slow and tedious process because all these popups contain forms and the validation is done server-side, which means I need to be able to submit the form and then re-render it if there's an error without breaking the whole page.
I just discovered there's a window.showDialogBox which works perfectly in Firefox (prevents you from clicking the main page until you close the dialog), but Chrome has already deprecated it, and IE only half supports it.
So, is there anything I can replace window.open with in the mean time to provide a better user experience, without re-writing every form to send and receive JSON via XHR?
You can use my showModalDialog polyfill using the brand new modal <dialog> element, which works in the latest Google Chrome. A <dialog> polyfill for older browsers is here.
You can use different codes for different browsers, like this:
if(navigator.userAgent.indexOf("MSIE") != -1){ //If the browser is IE
//Code for IE
}
else if(navigator.vendor == "Firefox"){ //If the browser is Firefox
//Code for Firefox
}
else if(navigator.vendor == "Google Inc."){ //If the browser is Chrome
//Code for Chrome
}
For IE, showModalDialog works just fine and it prevents you from clicking the main page until you close the dialog.
For Firefox, you can use, as you said, showDialogBox.
For Chrome, you can use the thing that niutech suggests.
Otherwise, if you use window.open, all the popup windows will be in the task bar so if they are hidden behind the window, just click on them in the task bar to make them visible.
here's my code:
/**
* May 2015: showModalDialog will not be supported any longer, so, if not available, we need to make a pure
* window.open and a catch which callbacks.
*
* In contradiction to other solutions, this "emulator" is capable of loading
* cross-origin urls such as oAuth2 redirect cascades, which can not be put in to iframes or dialogs due to
* their CSSP settings!
*
* Flow control of the caller needs to take care whether a window is returned or false
*
* #constructor showModalDialogHandler(callback) - callback is called, if window is closed.
*
*/
var showModalDialogHandler = function(callback)
{
this.modalDialogEmulator = null;
this.callBack = callback;
this.returnImmediately = false;
this.modalDialog = false;
this.maxRuns = 180;
this.intervall = 750;
this.force = false; // if set to true, emulate always.
this.chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
/**
* make the call, open a dialog, load etc.
*
* #param url - URL to load
* #param arg - args to pass to the window
* #param feature - featurelist as of window.open
* #return - erturns a window object (if modal dialogs are supported) or false otherwise
*
*/
this.callModalDialog = function(url, arg, feature) {
var self = this;
if ( !this.force && window.showModalDialog )
this.modalDialog = window.showModalDialog(url, arg, feature );
else
{
this.modalDialog = this.modalDialogEmulator(url, arg, feature );
window.setTimeout(function () {
self.modalDialog.focus();
}, 20);
/*
* Catch lose focus on main window. Modal dialog should at least
* stay in front of the opener. If the opener gets focus,
* window is either shuffled up or closed and reopend (chrome).
*
*/
jQuery(window).bind("focus", function() {
//console.log("opener focus");
if ( self.chrome )
{
// brute force: close and reopen, hope it will cope with that !!!
if( !self.modalDialog.closed )
{
self.modalDialog.close();
self.modalDialog = self.modalDialogEmulator(url, arg, feature );
}
}
else
{
if( !self.modalDialog.closed )
{
window.setTimeout(function () {
self.modalDialog.blur();
self.modalDialog.focus();
}, 30);
}
else
{
jQuery(window).unbind("focus"); // remove that listener, cpu-sucker.
}
}
});
}
if ( this.returnImmediately )
{
var runs = this.maxRuns;
var loop = setInterval(function() {
if(self.modalDialog.closed)
{
//console.log("close catched, callback:");
clearInterval(loop);
self.callBack();
}
if ( runs-- <= 0 )
clearInterval(loop); // infinitystopper
}, this.intervall );
return false;
}
else
return this.modalDialog;
};
/*
* showModalDialog is not longer supported, emulate with popup and
* a catcher with returnImmediately
*/
if ( this.force || !window.showModalDialog)
{
var self = this;
this.modalDialogEmulator = function(url, arg, feature) {
// console.log("window.ShowModalDialog not supported");
self.returnImmediately = true;
var opFeature = feature.split(";");
var featuresArray = new Array()
if (document.all)
{
for (var i = 0; i < opFeature.length - 1; i++)
{
var f = opFeature[i].split("=");
featuresArray[f[0]] = f[1];
}
}
else
{
for (var i = 0; i < opFeature.length - 1; i++)
{
var f = opFeature[i].split(":");
featuresArray[f[0].toString().trim().toLowerCase()] = f[1].toString().trim();
}
}
var h = "200px", w = "400px", l = "100px", t = "100px", r = "yes", c = "yes", s = "no";
if (featuresArray["dialogheight"]) h = featuresArray["dialogheight"];
if (featuresArray["dialogwidth"]) w = featuresArray["dialogwidth"];
if (featuresArray["dialogleft"]) l = featuresArray["dialogleft"];
if (featuresArray["dialogtop"]) t = featuresArray["dialogtop"];
if (featuresArray["resizable"]) r = featuresArray["resizable"];
if (featuresArray["center"]) c = featuresArray["center"];
if (featuresArray["status"]) s = featuresArray["status"];
var modelFeature = "height = " + h + ",width = " + w + ",left=" + l + ",top=" + t
+ ",model=yes,alwaysRaised=yes" + ",resizable= " + r + ",center=" + c
+ ",dependent=yes,dialog=yes,modal=yes,close=0"
+ ",status=" + s;
var model = window.open(url, "modal", modelFeature, null);
return model;
};
}
}
needs jQuery, at least.
you can check this link for jQuery Modal, to use this code, you need to include jquery-ui javascript and css files

Using new Image().src for click tracking

I am attempting to figure out why this click tracker isn't working. The code was written by another developer so I am not entirely sure if this ever did work.
function trackSponsor(o, p) {
(new Image()).src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
return false;
}
From what I can gather is that when this function is called it 'creates a new image' to fire a php script asynchronously. According to Firebug, the request is made however it is 'aborted' ~30ms in. The odd thing is that it will 'sometimes' work as in 1 in every 10+ regardless of the browser.
I would much rather fix this so that it works instead of re-writing it as an ajax request.
Any help is appreciated.
Thanks in advance.
EDIT
Because of tvanfosson's post that got me thinking. I have included the line which calls the click tracker below.
<a onclick="trackSponsor(60, 15077); goToNextStep(1988, 15077, 0); return false;" href="#">view</a>
the goToNextStep() actually changes the page. I am under the impression that it would only be executed after trackSponsor() had finished.
It's actually pretty trivial to rewrite as a get request using jQuery. Rewriting it will certainly help the next developer understand what's happening and might fix your problem. I'd need to know more about the contents of the variables -- perhaps they need to be urlEncoded? -- before I could help you any more on it. You might try urlEncoding them and see what happens.
function trackSponsor(o, p) {
var url = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
$.get(url);
return false;
}
EDIT: you might want to check that another handler isn't redirecting the browser to a new location when the event triggering the tracking is invoked. This would abort any pending requests on the page -- and might allow a few to succeed based on the timing of the requests and if the results are delivered before the page is unloaded.
"(new Image()).src = url;" just asks for browser to hit the url.
You should delay for a 50-100ms in order to be sure that tracking info were sent to the server.
function delay(a) {
for (var b = +new Date, c = 1; 0 < c; c++) {
if (0 == c % 1E3) {
var e = +new Date;
if (b > e) break;
if (e - b > a) break;
}
}
}
function trackSponsor(o, p) {
(new Image()).src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
delay(100);
return false;
}
I poked around Google Analytics’ ga.js, which does use the new Image() method similar to your script.
The only difference that I could see was in how the object is created. Google's script assigns the object to a variable.
var d=new Image(1,1);d.src=f;
Maybe give that a shot?
function trackSponsor(o, p) {
var i = new Image(1,1);
i.src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
return false;
}
It shouldn't make a difference, but is worth a shot.
Maybe try this, for avoiding Garbage Collection to make your log not be lost.
var sendLog = (function () {
var _unique = (function () { /* 产生唯一标识*/
var time = (new Date()).getTime() + '_',
i = 0;
return function () {
return time + (i++);
}
}());
var run = function (url) {
var data = window['imgLogData'] || (window['imgLogData'] = {}),
img = new Image(),
uid = _unique();
data[uid] = img; /* 防止img被垃圾处理*/
img.onload = img.onerror = function () { /* 成功或失败后销毁对象*/
img.onload = img.onerror = null;
img = null;
delete data[uid];
};
img.src = url + '&_cache=' + uid; /* 发送统计内容*/
};
return run;
}());
sendLog('http://log_');

Categories

Resources