$.post and $.get only letting title be changed, not logging? - javascript

In the following snippet of my code, I post to a link, from which it allows me to change the title, but will not call the function info() with the argument supplied, nor will it log in the console, please help with this code, thanks. Also, please note all the variables are defined and this code works 100% besides this, and it won't work with $.get rather than $.post either.
function info(text, state) {
$("<h4>"+text+"</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
$.post(buy, function(r) {
diff = event.timeStamp - last;
$(document).prop('title', 'Purchased '+info['itemName']+'!');
info('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
console.log('Purchased '+info['itemName']+' for '+info['expectedPrice']+' in '+diff+' milliseconds!');
})
--EDIT--
If I put console.log above info, the code works excluding the info() function, so the problem is possibly there

Try (this pattern)
// var last = $.now();
function info(text, state) {
$("<h4>" + text + "</h4>").appendTo("body");
if (state != "run") {
$("h2").text(text).fadeIn("slow").delay(30000).fadeOut();
}
// missing closing `{` at OP
};
$.post(buy, function (_info) {
// `_info` : return json object
// `info` : function declaration name
// diff = $.now() - last;
$(document).prop('title', 'Purchased ' + _info['itemName'] + '!');
info('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!'
, "run");
console.log('Purchased '
+ _info['itemName'] + ' for '
+ _info['expectedPrice'] + ' in '
+ diff + ' milliseconds!');
});
jsfiddle http://jsfiddle.net/guest271314/7vxb7336/

Related

Can't attach frida function to android native lib function

I'm building a frida js script that reads a json object containing directives to where to attach frida functions inside a native lib in an android APK. If I hardcode the libname and function name I can successfully attach to the function when it runs inside the app but for some reason I don't know why when I read the names from the json object the attachment doesn't occur. Assuming that I want to attach to a function named Java_sg_vantagepoint_uncrackable3_CodeCheck_bar inside libfoo.so.
The code that runs successfully:
Interceptor.attach(Module.findExportByName("libfoo.so", "Java_sg_vantagepoint_uncrackable3_CodeCheck_bar"), {
onEnter: function(args){
console.log('libfoo.so::Java_sg_vantagepoint_uncrackable3_CodeCheck_bar')
// this is logged when the function runs in the APP
if(args){
for(var arg in args){
console.log('args[' + arg + ']:')
console.log('Java_sg_vantagepoint_uncrackable3_CodeCheck_bar::args[arg] ' + args[arg])}
}
},
onLeave: function(args){
console.log('Leaving Java_sg_vantagepoint_uncrackable3_CodeCheck_bar...')
}
}
)
The code that doesn't work:
var params = {
"libs": ["libfoo.so"]
}
for(var lib in params.libs)
{
const currentLib = params.libs[lib]
Module.ensureInitialized(currentLib)
console.log('current lib: ' + currentLib)
var libExports = Module.load(currentLib).enumerateExports()
for(var i in libExports)
{
var currentLibExport = libExports[i]
if(currentLibExport.name.toLowerCase().includes('java'))
{
console.log('attaching to export: ' + currentLib + '::' + currentLibExport.name + ' at address: ' + currentLibExport.address)
Interceptor.attach(currentLibExport.address, {
onEnter: function(args){
console.log('onEnter ' + currentLib + '::' + currentLibExport.name)
if(args){
for(var arg in args){
console.log(currentLib + '::' + currentLibExport.name + '::args[arg] ' + args[arg])
}
} else
{
console.log('no args for ' + currentLib + '::' + currentLibExport.name)
}
},
onLeave: function(args){
console.log('onLeave ' + currentLib + '::' + currentLibExport.name )
}
}
)
}
}
}
Not only this doesn't attach to the function named Java_sg_vantagepoint_uncrackable3_CodeCheck_bar but even stranger during runtime it is logged the following:
onEnter libfoo.so::main
onLeave libfoo.so::main
which for me makes no sense because I didn't attach to the main function
Reference: https://www.frida.re/docs/javascript-api/#module

Passing arguments to Array.forEach callback function

someOperation.then(function(x) {
things.forEach(function(thing) {
//doing something with 'thing' that depends on variable 'x'
});
});
In the code above, how can I make the variable 'x' available inside the callback function? Or do I have to go back to using a for loop in this case?
It is available.
let x = {
name: 'Mike'
};
['Hello', 'Goodbye'].forEach(function(greeting) {
document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\n';
});
<pre></pre>
What you're using here is known as a closure and is a commonly used feature of Javascript. Basically, any function has access to any other variable in it's parent scope.
function log(msg) {
document.querySelector('pre').innerHTML += msg + '\n';
}
var global = 'global';
function firstLevel(third) {
var first = 'first';
// `global` is in the parent scope so we can access it
log(global + ' -> ' + first);
function secondLevel() {
var second = 'second';
// Same thing with `first` here
log(global + ' -> ' + first + ' -> ' + second);
// This even works with passed in arguments
log(global + ' -> ' + first + ' -> ' + second + ' -> ' + third);
// We can even change closed over variables
first = 'fourth?';
}
secondLevel();
log(first); // Notice that `first` changed.
}
log(global);
firstLevel('third'); // Notice how `third` is used in `secondLevel`
<pre></pre>
You can pass a "thisArg" as the second parameter to forEach so for instance:
let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
alert( this.a + thing );
}, x);
Might be helpful depending on what you are trying to do.

setTimeout giving unexpected identifier?

So I have this code that I am running inside of the google chrome console, and every time that I try to run it it give me unexpected identifier on line: 12. I went to that line and it is the setTimeout. I really don't know how to fix this, I tried to just call snipebot() but that didn't work either.
function snipebot(itemID, max_price){
var ItemURL = "http://www.roblox.com/Item.aspx?id=" + itemID;
$.get(ItemURL, function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= max_price){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + purchaseData['expectedPrice'] + ']');
});
}
}
setTimeout(function(){
snipebot(itemID, max_price);
});
};
snipebot(18426536, 140);
It's unexpected because your call to $.get hasn't been closed properly on the previous line:
function snipebot(itemID, max_price){
var ItemURL = "http://www.roblox.com/Item.aspx?id=" + itemID;
$.get(ItemURL, function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= max_price){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + purchaseData['expectedPrice'] + ']');
});
}
}); // <-- here
setTimeout(function(){
snipebot(itemID, max_price);
}, 2000); // <!-- See below
};
snipebot(18426536, 140);
Also note my second comment, where you've missed the 2nd parameter to setTimeout, namely how long to delay for. I've added in a two second delay as an example. Without this, it defaults to 0, which may or may not be what you intended.

How would I make this code efficient?

First off, sorry for it not being so neat, I am still learning the ropes of javascript.
I am running this code in the google chrome console, but it takes too much time to run it, is there anything I am doing, that I can fix to make it run faster?
function snipebot(page, max_page, max_price){
$.getJSON('http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=' + page, function(data){
$.each(data, function(index, item){
if (item['BestPrice'] <= max_price){
$.get('http://www.roblox.com/Item.aspx?id=' + item['AssetId'], function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= item['BestPrice']){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + item['BestPrice'] + ']' + item['Name'] + item['AssetId'] + ' user:' + purchaseData['seller-name'] + ' ' + '#' + new Date().toTimeString())
});
} else {
console.log("Detected purchase:" + item['Name'] + item['AssetId'] + ' ' + purchaseData['seller-name']);
}
});
};
});
setTimeout(function(){
snipebot(page + 1 > max_page ? 1 : page + 1, max_page, max_price);
});
});
};
snipebot(1, 4, 50);
In the worst case, a call to snipebot() makes 3 round trip to the backend. You should review your design and move some of your logic to the backend to reduce the round-trips.
if (item['BestPrice'] <= max_price){ ...
if (purchaseData['expectedPrice'] <= item['BestPrice']){ ...
Both conditions above can be tested at the backend and processed there.

relational database and oop javascript

i am trying to create a relational database while using oop in java script , yet i am encountered with some difficulties , this is the code ,
IT WAS WORKING BEFORE I CHANGED IT TO OOP
function DB() {
this.size;
this.row;
this.getsize = function() {
return this.size;
}
this.db = window.openDatabase('coupons', "1.0", 'database for coupons', 100000);
this.al = function() {
alert('al works');
}
this.add = function(table, id, name, email, fav) {
// alert("works");
// alert("INSERT INTO " + table + " VALUES(" + id + "," + name + ")");
this.db.transaction(function(ob)
{
ob.executeSql("SELECT * FROM " + table + " WHERE pid= " + id + "", [], this.dataHandler, this.errorHandler);
});
this.db.transaction(function(ob)
{
//alert(getsize());
if (this.size > 0) {
alert("user already exists")
} else {
ob.executeSql("CREATE TABLE IF NOT EXISTS " + table + " (pid INTEGER, pname TEXT, pemail TEXT,pfav)");
ob.executeSql("INSERT INTO " + table + " VALUES(" + id + "," + "'" + name + "'" + "," + "'" + email + "'" + "," + "'" + fav + "'" + ")");
alert("user addd successfuly");
}
}
);
}
this.errorHandler = function(error)
{
document.write("handling error " + error);
}
this.dataHandler = function(transaction, data)
{
// document.write("<table>");
//document.write("<tr><th>id</th><th>name</th></tr>")
// size = data.rows.length;
//for(i=0;i<size;i++)
// {
//Variables.call(this,data.rows.length,data.rows.item(0));
//Variables.call(7,6);
this.size = data.rows.length;
this.row = data.rows.item(0);
//return row;
// document.write(
// "<tr><td>"+row['pid']+"</td><td>"+row['pname']+"</td></tr>");
// }
//document.write("</table>");
}
this.getrows = function(n)
{
switch (n)
{
case 'pid':
return this.row['pid'];
break;
case 'pname':
return this.row['pname'];
break;
case 'pemail':
return this.row['pemail'];
break;
case 'pfav':
return this.row['pfav'];
break;
default:
}
}
}
the problem are as follows , hope you can help me out !!
1.after calling the function add , it does not go to dataHandler function .
2. in the add function i am unable to use local variables , how can i use the variable 'size' to check if the user exists in the database or not ?!! ,
hope you can help i have been in this code for 2 days !!! :(
Yes. You obviously can't access this.size in your function because you are using a anonymous function, so this is not related to your DB -oject but points to that anonymous function.
The same for your calls to this.dataHandler or this.errorHandler.
So you could just
this.db.transaction = function(ob)
to make it a method of your object which then will give you full access to the this - pointer of your DB - Object.
EDIT: Sorry, this would then point to the db object, of course, so this is not a solution.
But you can pass it your data - and errorHandler like this:
this.db.transaction(function() { ... }, this.errorHandler, this.dataHandler);
and avoid the call to this.size within the second transaction - statement by simply wrapping your call like:
if(this.size > 0) { alert('..'); } else { db.transaction(...) }
But: Your errorHandler and dataHandler must actually correspond to the right interface - definitions, take a look at:
http://www.w3.org/TR/2009/WD-html5-20090212/structured-client-side-storage.html

Categories

Resources