Why is this Javascript library available in browser but not in PhoneGap? - javascript

I have defined a library in Javascript that works great when I am in a browser but whose name isn't found when running under PhoneGap on my device.
The library is defined as so:
(function(bsdi, $) {
bsdi.SomeName = "XYZ";
bsdi.addDays = function (date, days) { ...stuff here...}
....
}(bsdi = window.bsdi || {}, jQuery));
Later, in a .js file that is loaded last, I have:
function knockoutFn() {
var self = this;
if (bsdi.SomeName == "XYZ") { <<--- CRASHES HERE, "bsdi not defined" but only on Device
...stuff here...
}
}
// Happens to use Knockout...
var koFn = new knockoutFn();
ko.applyBindings(koFn);
function init() {
if (isPhoneGap) {
document.addEventListener("deviceready", onDeviceReady, false);
}
else {
koFn.InitPage();
}
}
function onDeviceReady() {
// Now safe to use the Cordova API
koFn.InitPage();
}
What happens is that a normal web browser handles this just fine. However, when I download to my iPhone using the PhoneGap Build app, it gets to "bsdi.SomeName" and crashes because bsdi is not defined. I thought that my method for defining the bsdi library was correct but, obviously, there is something in PhoneGap that doesn't like this. Note that "isPhoneGap" is true and we do use the addEventListener on the device.
Any ideas are greatly appreciated!
UPDATE: On a hunch, I tried moving the bsdi object into the same .js file as the code that uses it. In this case, it finds the object and uses it correctly. When it is an external file, however, it fails. And yes, I have triple-checked that the file exists and is at the correct location. Again, it works fine in a browser!

If window.bsdi isn't defined, then (as posted in your question) your initialization code never ensures that window.bsdi is defined by the time the code is finished. All it does is add those properties to the new empty object passed in, but that won't have any effect on anything once the initialization function is finished.

Related

how to fix Error: java.lang.ClassNotFoundException on frida

I'm trying to bypass a root detection mechanism on an android app using Frida, I've tried so many different scripts (frida code share) and different approaches (like hiding root) with no luck!
So I tried to locate the class and method responsible for checking if the device is rooted or not and changing it's return value.
This is my script :
setTimeout(function() { // avoid java.lang.ClassNotFoundException
Java.perform(function() {
var hook = Java.use("app.name.RootUtils");
console.log("info: hooking target class");
hook.isRooted.overload().implementation = function() {
console.log("info: entered target method");
return Java.use("java.lang.Boolean").$new(false);
}
});
},0);
If I inject this code normally it won't work because it looks like the isRooted method will get called before it
If I use spawn to run the app and change this method return value it fails with error :
frida.core.RPCException: Error: java.lang.ClassNotFoundException: Didn't find class ...
I've also tried spawning the app and then using objection to run "android root disable" but it will return this error :
frida.core.RPCException: TypeError: cannot read property 'getApplicationContext' of null
at getApplicationContext (src/android/lib/libjava.ts:21)
I'm not sure if this is a problem with Frida or my system or ...
I think if I was able to make my main code runs at exactly after the class gets loaded (like using a loop to check or using a hook) the problem would be fixed but I don't know how to write that kind of code in js for frida.
I'm on macOS 11.5.1 using python 3.9 and installed latest version of frida and objection
I've tested on one rooted phone with android 10 and an emulator with android 6
I was able to solve this issue with a simple yet not very technical solution.
I used a setInteval to run my hooking over and over until it gets to work, (as #Robert mentioned, I also needed to wrap hooking inside a try catch to prevent the code from stoping after first try)
This may not work for everyone but since it worked for me I will post the final code, may it helps someone else in the future :)
Java.perform(function() {
var it = setInterval(function(){
try{
var hook = Java.use("app.name.RootUtils");
console.log("info: hooking target class");
hook.isRooted.overload().implementation = function() {
console.log("info: entered target method");
clearInterval(it);
return Java.use("java.lang.Boolean").$new(false);
}
} catch(e) {
console.log("failed!");
}
},200); // runs every 200milisecods
});
PS : you may need to change interval time to match your app needs, it worked for me with 200 miliseconds.
Sometimes app would do encryptions in its class loader, you may need to replace Java.classFactory.loader with the app's customized class loader in order to make Java.use function properly.
Here's how it's done:
Java.perform(function() {
//get real classloader
//from http://www.lixiaopeng.top/article/63.html
var application = Java.use("android.app.Application");
var classloader;
application.attach.overload('android.content.Context')
.implementation = function(context) {
var result = this.attach(context); // run attach as it is
classloader = context.getClassLoader(); // get real classloader
Java.classFactory.loader = classloader;
return result;
}
//interesting classes
const interestingClassPath = "com.myApp.SometingInteresting";
interestingClass = Java.use(interestingClassPath);
//do whatever you like here
})
Class not found
How do you know the class is app.name.RootUtils have you decompiled to app using Jadx or apktool? How about the method where RootUtils.isRooted() is called? Is there any special code that loads the RootUtils class e.g. from a non-standard dex file included in the app? If the class is loaded from a special dex file you could hook this dex loading mechanism and first execute it and then install your hook for RootUtils.isRooted().
Alternatively assuming RootUtils.isRooted() is called only from one other method and does not use special code for loading the RootUtils class you could hook that method and use the this hook to install install your RootUtils.isRooted() hook.
Error handling
The correct way to handle errors in JavaScript is using try catch block, not the setTimeout function:
Java.perform(() => {
try {
var hook = Java.use("app.name.RootUtils");
...
} catch (e) {
console.log("Failed to hook root detection" + e);
}
}
Regarding your problems hooking the class

How can I detect when an AngularJS app is finished loading a page using JavaScript?

I'm trying to write Robot Framework tests to cover certain use cases for a third party AngularJS app.
I have the requirement that I need to use Python 3.5+ and SeleniumLibrary (rather than the old Selenium2Library).
I've attempted to adapt the wait_until_angular_ready keyword from https://github.com/rickypc/robotframework-extendedselenium2library to work outside of the context of this library, updating it to work with Python 3.5+ and SeleniumLibrary.
The keyword executes the following JavaScript to check when Angular is Ready, but it seems to always return true immediately
var cb = arguments[arguments.length-1];
if(window.angular){
var $inj;
try {
$inj = angular.element(document.querySelector('[data-ng-app],[ng-app],.ng-scope')
||document).injector()
||angular.injector(['ng'])
} catch(ex) {
$inj = angular.injector(['ng'])
};
$inj.get = $inj.get||$inj;
$inj.get('$browser').notifyWhenNoOutstandingRequests(function() {
cb(true) // it's always returning here
})
} else {
cb(true)
}
This is called from within my version of the wait_until_angular_ready keyword which is located in a class which subclasses the SeleniumLibrary WaitingKeywords class.
The code which executes the Js looks like
WebDriverWait(self.driver, 100, 0.1). \
until(lambda driver: driver.execute_async_script(script), error)
Have I made a mistake here or is this not the correct way to check when angular has finished rendering the page? I will admit that I am not very familiar with AngularJS
Probably you resolved this issue, but if anyone in the future have the same inconvenience can use this library for Angular in Robot framework: https://github.com/Selenium2Library/robotframework-angularjs
you can use document.readyState , it will return "complete" as a response if the page is rendered completly.

Modernizr download file, but it is still undefined afterwards? (Only in IE9 after page postback)

I've got a jQuery plugin I made which will nicely format dates on elements with certain attributes on them. Overall it works, but I'm having some problems with Modernizr, but ONLY in IE and ONLY after a form postback.
Here's a snippet from the plugin where it uses the fantastic MomentJS library. Basically the first time the plugin is called, it will download the needed file then run the code to parse dates. If it is called any time afterwards and the library has already been downloaded, it can just go ahead and run the date parsing code.
function parseDates() {
var $items = this;
if (typeof moment !== "undefined") {
//If we are calling this at a time after page load, just run the function
setupDisplayDate();
} else {
//If the files have not been included yet, download them & call the function
//Load in a date library!
Modernizr.load({
load: SCRIPTS_PATH + "moment.min.js",
callback: setupDisplayDate
});
}
function setupDisplayDate() {
console.log("setupDisplayDate called! Moment is " + typeof moment);
$items.each(function () {
var $thisItem = $(this);
var formatter = $thisItem.data("date-format") || "MMMM Do, YYYY";
var ticks = parseInt($thisItem.data("date-ticks"), 10);
var formattedDate = moment(ticks).format(formatter);
$thisItem.text(formattedDate);
});
}
}
When I do this in IE9 only after a page postback, I get an error within the setupDisplayDate function saying that moment is not defined. What am I doing wrong?
I did find that if I do a timeout of 500ms it will work, but I shouldn't have to do that. I thought the whole point of the Modernizr.load feature was to download the code, and then make it available. It seems to download it and the fire my callback before it is available to use.
EDIT
Here's [a blog post about how IE9 will not properly dynamically added scripts: http://www.guypo.com/technical/ies-premature-execution-problem/
Any way around this?
Another Edit
It seems like the issues is actually regarding multiple calls to the load function and then the various callbacks firing out of order. There's an open issue on GitHub about it and this reproducible test case.

Issue with retrieving object data on IE 8 on Windows XP or 2003

This is an interesting problem that I am facing with JavaScript and IE8 on Windows XP and Windows 2003. I create an object on the page and then retrive information about that object (for example, its version). When trying to get the version, I am running this code:
var myObject = document.getElementById(objectId);
console.log(myObject.version);
What is interesting is that this code works on every single browser except IE8 on Windows XP and 2003. I've done some debugging and this is where things get interesting.
myObject is not null but myObject.version is undefined. So what I did is I added an alert in between so the code is now as follows:
var myObject = document.getElementById(objectId);
alert(myObject.version);
console.log(myObject.version);
The alert results in "undefined", however, the console.log is now resulting in the actual version. If I add an alert before this alert of anything (let's say alert("something")) then the second alert has the actual version now. I am assuming this is a timing issue (for some reason the object needs sometime to be able to provide the data stored in it?) but I am not sure what kind of timing issue this is or how to approach it.
Sorry for the long description but any help is appreciated.
document.getElementById doesn't return an object. It returns a DOM element. So, you expect to see a .version property in a DOM element, which by the official W3C specification is missing (or at least I don't know about this).
I'm not sure what you are expecting to see in .version, but if it is something custom then you should create a custom object like that:
var o = { version: "..." }
console.log(o);
You said that this may be a time issue. If that's true then I'll suggest to try to access the .version property after the DOM is fully loaded. You can use jQuery for the purpose:
$(document).ready(function() {
var myObject = document.getElementById(objectId);
alert(myObject.version);
console.log(myObject.version);
});
You can add a setTimeout in your function till the .version property is there.
var f = function(callback) {
var check = function() {
var myObject = document.getElementById(objectId);
alert(myObject.version);
console.log(myObject.version);
if(typeof myObject.version !== "undefined") {
callback(myObject.version);
} else {
setTimeout(check, 1000);
}
}
setTimeout(check, 1000);
}
What happens if you put the <script>...</script> tag with the js code at the end of the html file? In my opinion, the code is executed when the DOM is not ready. If you put it in the end, then it will be executed after it's loaded.

This object constructor is preventing my script from running

I'm working on a project (creating a browser based check list). One of my goals has been to write every piece by hand without a library like jquery or a mysql database.
Currently I'm trying to create on object for managing tasks. I'm not finished the primary function, but everything is closed, and I don't detect any errors. Furthermore, I'm haven't iterated it or called it's functions yet, so there's nothing to reference it yet. When I comment it out, the script runs normally.
I've included the xml request links up above and tested them successfully in a separate portion of the script.
I'm testing in firefox.
I'm writing this in SciTE
Here's the code:
function Task(name,node,childNode,divClass,content,onclick)
{
function retrieveTask(node,childNode)
{
var taskArray = [];
taskArray.push(xmlDoc.getElementsByTagName(name)[node].childNodes[childNode].nodeValue;)
taskArray.push(xmlDoc.getElementsByTagName(description)[node].childNodes[childNode].nodeValue;)
taskArray.push(xmlDoc.getElementsByTagName(complete)[node].childNodes[childNode].nodeValue;)
return taskArray;
}
function displayTask(name,content)
{
var task = retrieveTask(node,childNode);
var clickDiv = "";
formatDiv(name,"task",task[1],clickDiv);
task[2] === true ? formatDiv(name+1,"incompleteBox"," ",clickDiv) : formatDiv(name+1,"completeBox","O",clickDiv);
}
}
If anyone could give me some insight or tips that would be awesome. This isn't homework, it's a hobby, so it's a self teaching process.
...childNodes[childNode].nodeValue;)
should be );

Categories

Resources