javascript code analysis: getting the name of handler - javascript

I am to analyse a huge js script. I'm using deobfuscators and firebug, but this script is so complicated that it's difficult for me to understand anything. So my question is do you know any tool that would show me e.g. name of function that handles event I fire? Or maybe it's possible to write it myself?

Try (this pattern)
$(function () {
$(document).on("click.abc", "body", function def (e) {
var name = (e.handleObj.handler.name === ""
? "<i>event handler name:</i> " + "anonymous function"
: "<i>event handler name:</i> "+ e.handleObj.handler.name);
var namespace = (e.handleObj.namespace
? "<i>event namespace:</i> " + e.handleObj.namespace
: "<i>event namespace:</i> " + e.handleObj.namespace);
$("body").append("<br>"
+ "<i>event type:</i> "
+ e.type + "\n"
+ name + "\n"
+ namespace);
$.each($._data($(document)[0], "events"), function(k, v) {
console.log(k
, v[0].data
, v[0].guid
, v[0].handler.name
, v[0].namespace
, v[0].origType
, v[0].selector
, v[0].type);
});
});
});
jsfiddle http://jsfiddle.net/guest271314/ykcnbuqp/

Related

The onstorage event doesn't get fired

The onstorage event doesn't fire in either Firefox nor Chrome when setting a local storage variable event with a value different than before.
window.addEventListener('storage', () => {
console.log('onStorage raised');
});
//window.onstorage = e => {
// console.log('onStorage raised');
//}
localStorage.setItem('date', new Date());
https://jsfiddle.net/Brobic/fot9vzm6/1/
If you are the one setting localStorage, you can create your own event. Although this might be a little overkill as you could always just use this method to call a function also instead of creating an event. I used the older event style since it is more compatible.
function setStorage(k, v) {
const event = document.createEvent('Event');
event.initEvent('storageChanged', true, true);
localStorage.setItem(k, v);
document.dispatchEvent(event);
}
window.addEventListener('storageChanged', (e) => {
console.log('storageChanged raised');
});
setStorage("date", new Date())
console.log(localStorage.getItem('date'))
As written here:
https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event
Event is fired is storage is changed by ANOTHER document, not self.
As #Quercus pointed out, the event won't fire on it's own page, that's why I use localDataStorage, a handy wrapper for the HTML5 localStorage API that conveniently fires change events on the same page/tab/window in which the storage event occurred. (Disclaimer: I am the author of the interface.)
Once you install localDataStorage, this sample code will let you see those change events:
function nowICanSeeLocalStorageChangeEvents( e ) {
console.log(
"subscriber: " + e.currentTarget.nodeName + "\n" +
"timestamp: " + e.detail.timestamp + " (" + new Date( e.detail.timestamp ) + ")" + "\n" +
"prefix: " + e.detail.prefix + "\n" +
"message: " + e.detail.message + "\n" +
"method: " + e.detail.method + "\n" +
"key: " + e.detail.key + "\n" +
"old value: " + e.detail.oldval + "\n" +
"new value: " + e.detail.newval + "\n" +
"old data type: " + e.detail.oldtype + "\n" +
"new data type: " + e.detail.newtype
);
};
document.addEventListener(
"localDataStorage"
, nowICanSeeLocalStorageChangeEvents
, false
);
It works if you have another page that modify the storage
page1.html
window.addEventListener('storage', () => {
console.log('onStorage raised');
});
page2.html
localStorage.setItem('date', new Date());
You can read about at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onstorage

How to get Html code after javascript has modified it?

I want to get the HTML code of a webpage after it has been modified (similar to one that we see in inspect element tab of a browser) and I want to do it programatically (if possible using python or any other programming language). Can someone suggest how I might be able to proceed with this? I know its possible since browsers are able to do it.
As the server has no access to client window after client-side changes, you have to use client side languages.
In jquery:
var fullCode= "<html>" + $("html").html() + "</html>";
if you want also to include the Doctype:
var node = document.doctype;
var fullCode = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
fullcode += "<html>" + $("html").html() + "</html>";
Thanks to this
Using JQuery you can achieve this by the following code
$(document).ready(function(){
var html = "<html>"+$('html').html()+"</html>";
});

Clicking on an element to reveal additional .get information

I'm trying to work through the 2nd question on this set of problems. I have to be able to click on a legislator's name and have additional information about him/her show up. Here's what I have so far.
$(function() {
$("form#get-zip").submit(function() {
var zip = $("input#zip").val();
$.get("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip, function(responseText) {
responseText.results.forEach(function(legislator) {
$("ul#legislators").append("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "</li>");
$("li").click(function() {
$(this).append("<p>Party: " + legislator.party + ", District: " + legislator.district + "</p>");
});
});
});
return false;
});
});
The problem is that when I click on a legislator's name it reveals information about all the legislators in the list rather than the particular legislator I clicked on. This is my first experience with A.P.I.s and I'm very much still a novice programmer. I'm finding all these moving parts to be very mentally exhausting. So I really appreciate any help I can get with this. Thanks.
I would suggest building out all your html on submit, even the details that appear below each legislator. Then hide all that extra detail. And set up the function of your li's to show the relative details.
$(function() {
$("form#get-zip").submit(
function() {
var zip = $("input#zip").val();
$.getJSON("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip,
function(responseText) {
$.each(responseText.results,
function(i,legislator) {
var newEl = $("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "<p>Party: " + legislator.party + ", District: " + legislator.district + "</p></li>");
newEl.appendTo("ul#legislators");
$("ul#legislators li").last().find("p").hide(); // hide the last added one
}); // end each
}); // end get function
}); // end submit function
$("ul#legislators").on("click", "li",
function() {
var details = $(this).find("p");
if (details.is(":visible")) {
details.hide();
} else {
details.show();
}
}); // end click function
}); // end document ready function
When the click event fires, the legislator variable no longer contains the data you looking for.

Put javascript on page from code behind

I have some other javascript functions that are being set on the onfocus and onblur events of the textbox that I am using. In these functions it calls a generic javascript function that is not related to any controls. I want to know how to just simply spit this function out to the html of the page from the code behind. Something like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "?????", getCounter);
EDIT: Here is what I mean
public class MVADTextBox : TextBox
{
protected override void OnLoad(EventArgs e)
{
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetCounter(input)", getCounter);
var onBlur = "<script language=\"javascript\"> function PopulateField(input) {if (input.value == \"\") {input.value = input.defaultValue; input.className = 'sampleText'; } } </script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnFocus", onFocus);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnBlur", onBlur);
}
}
The on blur method is getting sent to the page.
Answer:
I believe that Page.ClientScript has been deprecated. You should be using ClientScriptManager.
Replace your "?????" with the name of the script. Honestly, the name of the script is almost useless (unless you need to check for its existence later on).
ClientScriptManager.RegisterStartupScript(this.GetType(), "myCount", getCounter);
Usage Clarification:
//You must surround your code with script tags when not passing the bool param
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"<script>alert('Hey')</script>");
// The last param tells .Net to surround your
// code with script tags (true) or not (false)
ClientScriptManager.RegisterStartupScript(this.GetType(),
"myCount",
"alert('Hey')", true);
Additional Information:
Signatures from MSDN:
public void RegisterStartupScript(
Type type,
string key,
string script
)
public void RegisterStartupScript(
Type type,
string key,
string script,
bool addScriptTags
)
See: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
I think you need to use the ClientScriptManager.RegisterClientScriptBlock method
Try this
EDITED:
var getCounter = "<script language=\"javascript\">" +
"function GetCounter(input) {" +
//this function gets the number of special characters taht are in a row.
//it is only the grouping of characters that are right after your current position
"var textbox = document.getElementById(input.id);" +
"var mask = textbox.getAttribute('Mask');" +
"var inputCharacters = textbox.getAttribute('InputCharacters');" +
"var tbid = \"#\" + input.id;" +
"var position = $(tbid).caret().start;" +
"var counter = 0;" +
"for (var i = position; i < mask.length; i++) {" +
" if (mask[i] != '#') {" +
" counter++;" +
" if (mask[i + 1] == '#') {" +
" break;" +
" }" +
" }" +
"}" +
"return counter;" +
" }" +
"</script>";
this.TextBox1.Attributes.Add("OnFocus", "GetCounter(this);");
if (!ClientScript.IsClientScriptBlockRegistered("getCounter")) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "getCounter", getCounter, false);
}
You would put the actual function definition, which you already have in getCounter. Note that the second parameter which you currently have as "????", as James pointed out, is for the script's key, which must be unique from all other scripts registered for this type. The third parameter is the script itself, and the fourth determines whether script tags are to be added, which needs to be false, since you already added them.
Page.ClientScript.RegisterStartupScript(this.GetType(),
"someKeyForThisType", getCounter, false);

jQuery callbacks messing with variable scopes and functions?

Good morning people - I've been having this problem for hours and I can't isolate it.
I have this piece of jQueryzed JavaScript:
jQuery(document).ready(function() {
var validated = 1;
jQuery('#help_continue').click(function() {
jQuery('#step' + validated + ', #step' + validated + '_help').fadeOut(200, function() {
jQuery('#step' + validated + '_help').removeClass('visible').find('.visible').removeClass('visible');
jQuery('#step' + (validated + 1) + '_help').addClass('visible');
jQuery('#step' + (validated + 1) + '_help div:first').addClass('visible').css({display: 'block'});
jQuery('#step' + (validated + 1) + ', #step' + (validated + 1) + '_help').fadeIn(200);
});
});
});
All good, nothing too fancy. If bound to HTML, it works as expected.
The thing is that, when I add this to the mix:
jQuery(document).ready(function() {
var validated = 1;
jQuery('#help_continue').click(function() {
jQuery('#step' + validated + ', #step' + validated + '_help').fadeOut(200, function() {
jQuery('#step' + validated + '_help').removeClass('visible').find('.visible').removeClass('visible');
jQuery('#step' + (validated + 1) + '_help').addClass('visible');
jQuery('#step' + (validated + 1) + '_help div:first').addClass('visible').css({display: 'block'});
jQuery('#step' + (validated + 1) + ', #step' + (validated + 1) + '_help').fadeIn(200); alert(validated); // this...
});
validated++; // ...and this.
});
});
The alert it shown TWICE, and the "validated" variable is NEVER = 1 inside the function - always 2.
I'm no JavaScript guru for sure, but I definitely know that that's just plain wrong, unless I'm missing something. I come from a PHP background, and I know that JavaScript has its idiosyncrasies, but this is just weird.
I'm using jQuery 1.5 if it matters. Anyone knows what's happening?
The code you pass as callback to fadeOut is only executed after ~200ms timeout. But the the code is not blocking. I.e. everything inside the click handler, also statements after the call to fadeOut, is executed immediately.
jQuery('#help_continue').click(function() {
// first
jQuery('....').fadeOut(200, function() {
// second
});
validated++; // first
});
But this should not show the alert twice... anyway, if you want to increment validate on click, but it should have the the correct value when the fadeOut callback is called, you can do so with an immediate function:
jQuery('#help_continue').click(function() {
(function(validated) {
jQuery('....').fadeOut(200, function() {
// ...
});
}(validated));
validated++;
});

Categories

Resources