How to make sense of this javascript code [duplicate] - javascript

My question is how can I decode this JavaScript and how is encoded (with which program or online tool).
Here is the JavaScript that I want to decode:
http://pastebin.com/hZvKySjj

Every obfuscated script needs some kind of eval. In here, the lines
_L = 'constr\x75\x63\x74\x6F\x72';
[][_L][_L](_Z[_h._t4](_F))();
are doing this. _L is the string "constructor", and [].constructor.constructor is the Function constructor. It will be called with the decoded script, and the resulting function will be called. We can substitute it with an alert, paste the script in the console*, and wait for the result - we don't even need to understand how the decoding works. In your case, the result is (yes, including all the comments and linebreaks):
var alarm ="0";
var content = document;
if ((content.getElementById("wrapper") != null))
{
document.getElementById('wrapper').style.display = 'block';
}
function a ()
{
if ((content.getElementById("links") != null))
{
var temp = content.getElementById("links").innerHTML;
if ((temp.indexOf('nofollow')+1) > 0) alarm = "1";
else if ((temp.indexOf('noindex')+1) > 0) alarm = "1";
}
else alarm = "1";
}
function b ()
{
if ((content.getElementById("aa") != null) && (content.getElementById("ab") != null))
{
temp = document.getElementById("aa").href;
if ("http://uc-portaller.ru/" != temp) alarm = "1";
temp = document.getElementById("ab").innerHTML;
if ("скрипты для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
function c ()
{
if ((content.getElementById("ba") != null) && (content.getElementById("bb") != null))
{
temp = content.getElementById("ba").href;
if ("http://austere.ru/" != temp) alarm = "1";
temp = content.getElementById("bb").innerHTML;
if ("доска объявлений" != temp) alarm = "1";
}
else alarm = "1";
}
function d ()
{
if ((content.getElementById("ca") != null) && (content.getElementById("cb") != null))
{
temp = content.getElementById("ca").href;
if ("http://www.for-creative.com/" != temp) alarm = "1";
temp = content.getElementById("cb").innerHTML;
if ("темы для ucoz" != temp) alarm = "1";
}
else alarm = "1";
}
a ();
if (alarm == "0") b ();
if (alarm == "0") c ();
if (alarm == "0") d ();
if (alarm == "1") prompt('Нарушены условия использования, по всем вопросам обращайтесь в ICQ:', '376880395');
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=0)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
$.fn.tabs = function () {
return this.each(function () {
var $tabwrapper = $(this);
var $panels = $tabwrapper.find('> div');
var $tabs = $tabwrapper.find('> ul a');
$tabs.click(function () {
$tabs.removeClass('selected');
$(this).addClass('selected');
$panels
.hide() // hide ALL the panels
.filter(this.hash) // filter down to 'this.hash'
.show(); // show only this one
return false;
}).filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
};
$(document).ready(function () {
// console.log(window.location.hash);
$('div.tabs').tabs();
});
*) Of course you need to be sure what you're doing. There's always a small risk that it's a malicious script, and you might have not found all evals. #jfriend00's tip on executing the decoding snippets line-by-line is a safer way.

The only way I know of to understand what this code does is to find a safe environment (in case the code has malicious intent) and execute it line-by-line in a debugger and watch what it does as it deobfuscates itself to turn itself into normal javascript. The variable names will often stay obscured, but the giant string in _O will get decoded into something (probably javascript code).

Have a look at: http://www.labnol.org/software/deobfuscate-javascript/19815/
They show you how can you do something like that, it's basically a matter of using chrome debugger to "beautify" the code and make it easier to read.
Some versions of chrome don't have the command on a context menu, just look for the command "Pretty print" (has a icon like -> {})
Once done that, you can use a javascript console to evaluate small snippets of code to reverse engineer it. Eg. the expression (at the beginning of your code)
1) (s\u0065lf + ([] * 0) * 1)
2) '\x5B'
3) ((s\u0065lf + ([] * 0) * 1)[0 ^ 0] == '\x5B')
returns this string on my browser
1) "[object Window]0"
2) "["
3) true
Just find the starting point and follow from there. Obfuscated code follows the same rules as normal one, it's just all messed up.

Related

How to set a value of a variable in a "child" javascript file from the "parent"?

In my index.php I have a script which toggles a sidebar.
$(function() {
// Open the Sidebar
$(".sidebar.right").trigger("sidebar:open");
// Toggle the Sidebarbutton to close
$(".open-close-button").toggleClass("open");
count = "1";
});
There is a "open/close" button which toggles the sidebar aswell. - Now, if i set the sidebar to "open" I need to tell the toggle-button to close, if someone clicks it - and I do that by setting "count" to "1".
"Count" is a "global-variable" - I think. I´m new to javascript, but it´s in no function. Look here, thats the "sidebar-toggle-script" sidebarhandlers.js:
var count = "0";
var open = "open";
var close = "close";
$(".sidebaropenclose").on("click", function () {
var $this = $(this);
var side = $this.attr("data-side");
if (count == "0") {
$this = $(this);
side = $this.attr("data-side");
$(".sidebar." + side).trigger("sidebar:" + open);
count++;
return false;
}
if (count == "1") {
$this = $(this);
side = $this.attr("data-side");
$(".sidebar." + side).trigger("sidebar:" + close);
count = 0;
return false;
}
In the "header" of my "index.php" I initialize the script with:
<script src="js/sidebarhandlers.js"></script>
The question is how i send the "count" from my "index.php" to "sidebarhandlers.js". - My version doesn´t work.

print javascript while loading

This is my code:
function myFunction(text, word){
var pos1;
do{
pos1 = text.indexOf(word);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
}
}while(pos1 == -1);
}
myFunction(text, "sun");
myFynction(text, "rain");
myFynction(text, "gold");
myFynction(text, "hello");
myFynction(text, "laptop");
myFynction(text, "tree");
I get text from file_get_contents of a page.
This page is continuously updating so, slowly, i will find those words through myFunction. What I want is to print those function meanwhile they finish
I really don't know if it's possible to use javascript to continuously monitor the HTML that is being loaded into the current page. It would require a few tests. However this would be my approach. (This function stops after finding one of the words in the array and displaying the pos)
var words = ['sun', 'rain', 'gold', 'HTML'];
function myFunc() {
var text = document.body.innerHTML;
var pos1;
for (var i=0; i < words.length; i++) {
pos1 = text.indexOf(words[i]);
if(pos1 !== -1){
document.getElementById("id1").innerText = pos1;
break;
}
}
if (pos1 === -1) {
// wait 1 second, try again
setTimeout(myFunc, 1000);
}
}
myFunc();
<div id='id1'></div>

How do I make text inside the title tag animate using JavaScript?

How do I show a scrolling (moving) message in the title?
<title>Welcome to Some title</title>
Translate the titlebar into a dynamic that displays additional information using JavaScript (without any CSS).
Here's an eye catching example to get your visitors back when your web page tab is not active within the browser (onblur). This script will animate the original title text with an intro, the original title text is restored when the tab is returned to active state (focus). When the tab is clicked the original page title is restored. For social media sharing it is highly recommended to include the original page title text with the prefaced animated text (onblur).
$(function() {
var origTitle, animatedTitle, timer;
function animateTitle(newTitle) {
var currentState = false;
origTitle = document.title; // save original title
animatedTitle = "Hey There! " + origTitle;
timer = setInterval(startAnimation, 2000);
function startAnimation() {
// animate between the original and the new title
document.title = currentState ? origTitle : animatedTitle;
currentState = !currentState;
}
}
function restoreTitle() {
clearInterval(timer);
document.title = origTitle; // restore original title
}
// Change page title on blur
$(window).blur(function() {
animateTitle();
});
// Change page title back on focus
$(window).focus(function() {
restoreTitle();
});
});
You can add marque in the title bar text through JavaScript. See it in the blog post Add Scrolling Marquee Effects Text to Title Bar.
The unmodified contents of that page, except for the formatting:
/*
Now you can add moving text to title bar of browser for your website or blog.
Here is the code to do this. Add this code in your website or blog in a widget
(after replacing YOUR TEXT with your desired text).
*/
<script language=javascript>
var rev = "fwd";
function titlebar(val){
var msg = "YOUR TEXT";
var res = " ";
var speed = 100;
var pos = val;
msg = " |-"+msg+"-|";
var le = msg.length;
if(rev == "fwd"){
if(pos < le){
pos = pos+1;
scroll = msg.substr(0,pos);
document.title = scroll;
timer = window.setTimeout("titlebar("+pos+")",speed);
}
else {
rev = "bwd";
timer = window.setTimeout("titlebar("+pos+")",speed);
}
}
else {
if(pos > 0) {
pos = pos-1;
var ale = le-pos;
scrol = msg.substr(ale,le);
document.title = scrol;
timer = window.setTimeout("titlebar("+pos+")",speed);
}
else {
rev = "fwd";
timer = window.setTimeout("titlebar("+pos+")",speed);
}
}
}
titlebar(0);
</script>
Here's another one. Only goes forward though...
To use: Link to the file and write this line of code
var title = new MovingTitle("Desired title... ", 300, 10);
title.init();
First parameter is the desired text, next one is the update interval, 10 is the number of visible letters...
function MovingTitle(writeText, interval, visibleLetters) {
var _instance = {};
var _currId = 0;
var _numberOfLetters = writeText.length;
function updateTitle() {
_currId += 1;
if(_currId > _numberOfLetters - 1) {
_currId = 0;
}
var startId = _currId;
var endId = startId + visibleLetters;
var finalText;
if(endId < _numberOfLetters - 1) {
finalText = writeText.substring(startId, endId);
} else {
var cappedEndId = _numberOfLetters;
endId = endId - cappedEndId;
finalText = writeText.substring(startId, cappedEndId) + writeText.substring(0, endId);
}
document.title = finalText;
}
_instance.init = function() {
setInterval(updateTitle, interval);
};
return _instance;
}
heres mine:
function animateTitle(Title = "Hello, World!", delay = 300) {
let counter = 0;
let direction = true;
aniTitle = setInterval(function () {
if (counter == Title.length)
direction = false;
if (counter == false)
direction = true;
counter = (direction == true) ? ++counter : --counter;
newtitle = (counter == 0) ? " " : Title.slice(0, counter);
document.title = newtitle;
}, delay)
}

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

Getting Javascript/jQuery scrolling function to work on successive divs

I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.

Categories

Resources