Javascript console.log() on HTC Android devices and adb logcat - javascript

I am developing the application in HTML which is calling the console.log() from Javascript to provide me logs during the development about what happens in the web page code.
Unfortunately when I use the adb logcat command to check logs I can see output from all other applications, but not the output from my JavaScript code. I can see even the log from web browser that the page is loaded, but not console.log() output from my JavaScript code executed in the web browser.
According to information on this page (http://developer.android.com/guide/webapps/debugging.html) it should work.
I am testing on HTC WildFire and HTC Desire HD.
Edited after more then 6 months
After some time and experience with different devices (phones, TVs, set top boxes, WebViews, UIWebViews...) my advice is to do the remote logging from JavaScript and not relying on the console.log() or other methods - see the nice trick with the image loading here.
Do not miss the presentation here
Hope this helps!
STeN

In the default browser on Android 2.3.3 (and presumably from then on) you can simply use the built in javascript console:
open the browser
go to your webpage
type about:debug in the address bar and hit enter
you'll see a section for debug options appear if you go into the browser app's settings
tick "Show JavaScript Console" if not already enabled
refresh your webpage
At the top, you'll see a bar labeled "JavaScript Console".

I have been using three different HTC phones, almost exclusively, and have never had this issue. Here are a few things to check:
Make sure USB debugging is enabled.
Make sure your Webview has a WebChromeClient set. The browser used in Webview does not implement console.log().
It should be easy to see the output of adb logcat, but to make it easier, filter the output.
Turn on USB debugging:
Disconnect your device from your computer.
Go to Settings -> Applications -> Development -> Select "Enable USB Debugging"
Plugin to computer. (Make sure you have the correct drivers installed to use ADB - more info here: http://developer.android.com/guide/developing/device.html)
Set a WebChromeClient that overrides onConsoleMessage():
//Set the output prefix so you can filter adb logcat results later
public static final String TAG = "Your-Application-Name";
myWebView = (WebView) findViewById(R.id.webview);
//Not going to have much luck running JS without this:
myWebView.getSettings().setJavaScriptEnabled(true);
//Override onConsoleMessage() to output to the Log.
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(TAG, cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
});
More info on onConsoleMessage() here: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(java.lang.String, int, java.lang.String)
More info on debugging in general here: http://developer.android.com/guide/webapps/debugging.html
Filter the output of adb logcat:
adb logcat tag-name:log-level *:S
tag-name matches the string specified in Log.x
log-level matches the log level you indicated when calling Log.x <---
Example relating to code above:
adb logcat Your-Application-Name:D *:S
This will show all d level logs for the matching tag, Your-Application-Name, and silence everything else.
More info on adb filtering here:
http://developer.android.com/guide/developing/tools/adb.html#logcat
Hope it helps! I know it was a bit of summarizing of the other answers, but, the fact is, it takes all of the steps to make it work. :)

I had the same problem, I solve it by doing the following:
1/ when you initialize your webview, add a javascript bridge class:
appView.addJavascriptInterface(new JSBridge(), "JSBridge");
2/ create the class JSBridge with a log function
class JSBridge {
public void log(String msg){
Log.d(msg);
}
}
3/ in your javascript you can now call
JSBridge.log("my log message");
Might be a bit overkill for your problem, but you can also do a LOT more with that solution

Logcat generates a lot of stuff on devices in addition to yours so you may have to filter this.
You can try to "grep" your log output if you've tagged it.
For example: acording to your article the output should look like:
Console: Hello World http://www.example.com/hello.html :82
If you use the command (assuming you are using a Linux, Mac OS or anything else with a grep command)
adb logcat | grep -i "console"
it will reduce the output to the keyword specified within these quotation marks. If you add a unique tag to your output you can also filter this so you get only things you want to see.
[ctrl]+c
will stop this logcat process.

See this: How to display console.log() output in PhoneGap app using Eclipse and HTC Desire HD?
It seems that console.log is disabled
on HTC devices running Android 2.2.
You can get around it by using remote debugging in jsconsole.com.

Try the following:
1) Open the devices tab and make sure that the device you have connected is selected/highlighted.
2) Make sure USB Debugging is enabled on your device. Here is what you need to do for this:
2a) From the Home screen, press MENU, and then tap Settings > Applications > Development.
2b) Make sure the USB debugging check box is selected.

Related

Aw, snap error in chrome while insert value into web sql using executeSql

I am creating a sqlite editor for android application, it is execute correctly still yesterday and finally just I tried to backup the chrome websql db so just copy the files from the following path "C:\Users\merbin.SERVER\AppData\Local\Google\Chrome\User Data\Profile 1\databases" and "C:\Users\merbin.SERVER\AppData\Local\Google\Chrome\User Data\System Profile\databases". Today I got the Aw, snap error on chrome, I debug the error and found, the error occur when I trying to create a table or inserting data into the database. But select query is execute perfectly. Some code examples are
query="insert into tbl(Type) values('Test')";
insert_query(query,insert_success,insert_fail);
function insert_query(query,succ_fun,fail_fun)
{
db.transaction(function(tx,result)
{
tx.executeSql(query, [],
function(tx,result)
{
eval(succ_fun)(result)
});
},eval(fail_fun));
}
function insert_success(result)
{
debugger;
$("#ex_area").empty();
$("#ex_area").append(result.rowsAffected+" Row(s) Affected.<br> Last Inserted ID is "+result.insertId);
alert("Insert Success");
return false;
}
function insert_fail(result)
{
debugger;
$("#ex_area").empty();
$("#ex_area").append("<span class='error'>"+result.message+"<br> Code : "+result.code+"</span>");
}
After that "eval(succ_fun)(result)" line I getting the Aw, snap error. screenshot is shown below.
image 1 Error on the Next Line Execution Screenshot
image 2 From previous line I am getting this error
Note : I think after update the chrome I have this problem.
I have solve this problem running the code through localserver. First the chrome allow to access the websql without using any server, but recent update chrome has change that rule. So must need any local server like xampp,wamp,IIS or etc...
by running the code through localserver: your JavaScript hosted through local server or the database or both
Create a new Google Chrome shortcut on your desktop.
Right click it, then click properties.
Add -allow-file-access-from-files to the end of the Target.
The end of the target should look like this:
\chrome.exe" -allow-file-access-from-files
Go into Task Manager.
Click Details.
End every single chrome.exe which is running.
Open up Google Chrome using the new shortcut you created.
Open up your website which uses WebSQL.
This worked for me.
Warning:
-allow-file-access-from-files lets Google Chrome have access to all of the files on your computer. ONLY, ONLY use this shortcut for developing. Do not browser the web, especially to untrusted websites, while you have this feature activated.
To deactivate it:
Go into task manager and end all chrome.exe's then open up chrome with a normal shortcut.

Facebook app browser debugging [duplicate]

I'm developing website with a lot of HTML5 and CSS3 features. I'm also using iframe to embed several content on my website. It works fine if I open it using Chrome/Firefox/Safari mobile browser. However, if I share on facebook (post/page) and I opened it up with Facebook application with Facebook Internal Browser, my website is messed up.
Is there any tools or way to debug on Facebook Browser? Thanks.
This is how you can do the debugging yourself. It's painful, but the only way I've come across so far.
tl;dr Get the Facebook App loading a page on your local server so you can iterate quickly. Then print debug statements directly to the page until you figure out what is going on.
Get a link to a page on your local server that you can access on your mobile device (test in mobile safari that it works). See this to find out your local IP address How do you access a website running on localhost from iPhone browser. It will look something like this
http://192.xxx.1.127:3000/facebook-test
Post that link on your Facebook page (you can make it private so your friends aren't all like WTF?)
Click the posted link in the Facebook mobile App and it will open up in Facebook's mobile browser
Since you don't have a console, you basically need to print debug statements directly to the page so it is visible. Put debug statements all over your code. If your problems are primarily related to CSS, then you can iteratively comment out stuff until you've found the issue(s) or print the relevant CSS attributes using JavaScript. Eg something like (using JQuery)
function debug(str){$('body').append("<br>"+str);}
Quite possibly the most painful part. The Facebook browser caches very aggressively. If you are making changes and nothing has happened, it's because the content is cached. You can sometimes resolve this by updating the URLs, eg /facebook-test-1, /facebook-test-2, or adding dummy parameters eg /facebook-test?dummy=1. But if the changes are in external css or js sheets it sometimes will still cache. To 100% clear the cache, delete the Facebook App from your mobile device and reinstall.
The internal browser the Facebook app uses is essentially a uiWebView. Paul Irish has made a simple iOS app that lets you load any URL into a uiWebView which you then can debug using Safari's Developer Tools.
https://github.com/paulirish/iOS-WebView-App
I found a way how to debug it easier. You will need to install the Ghostlab app (You have a 7-day free trial there, however it's totally worth paying for).
In Ghostlab, add the website address (or a localhost address) you want to debug and start the session.
Ghostlab will generate a link for access.
Copy that link and post it on Facebook (as a private post)
Open the link on mobile and that's it! Ghostlab will identify you once you open that link, and will allow you to debug the page.
For debugging, you will have all the same tools as in the Chrome devtools (how cool is that!). For example, you can tweak CSS and see the changes applied live.
If you want to debug a possible error, you can try to catch it and display it.
Put this at the very top of your code:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
alert(message);
}
}
(Source: MDN)
This will catch and alert your errors.
Share a link on Facebook (privately), or send yourself a message on Facebook Messenger (easier). To break the cache, create a new URL every time, e.g. by appending a random string to the URL.
Follow the link and see if you can find any errors.
With help of ngrok create temporary http & https adress instead of your ordinary localhost:3000(or other port) and you could run your app on any devices. It is super easy to use.
and as it was written above all other useful information you should write somewhere inside div element (in case of React I recommend to put onClick on that div with force update or other function for getting info, sometimes it helps because JS in FB could be executed erlier than your information appears). Keep in mind that alerts are not reliable, sometimes they are blocked
bonus from ngrok that in console you will see which files was
requested and response code (it will replace lack of network tab)
and about iFrame.If you use it on other domain and you rely on cookies - you should know that facebook in-app browser blocks 3rd party cookies
test on Android and iOS separately because technicaly they use different browsers

How do I turn off the console logging in App Engine Channel API?

I've implemented the Channel API w/ persistence. When I make a channel and connect the socket (this is on the real app, not the local dev_appserver), Firebug goes nuts with log messages. I want to turn these off so I can see my OWN logs but cant find any documentation on how to disable the Channel API console logging.
one thing I'm probably doing differently than most is that I'm connecting cross-domain... which the Channel API supports (note the first message in the stream... if you can view that pic)
Does anyone know?
UPDATE
I finally realized that my code was creating two channels and trying to open/connect them both at the same time... and that was why I was getting a flood of messages. I didn't mean to do this (I know the rules: https://developers.google.com/appengine/docs/python/channel/overview#Caveats )... it was a bug... and once I fixed it, the messages went back to manageable level.
yay
There doesn't appear to be a way to shutoff the Firebug timeStamp log. One way to solve this problem is to edit the code and remove this functionality yourself:
Unpack the extension to a directory in your Mozilla Firefox Profile:
Change directory to your Firefox profile extensions directory. On Ubuntu, this would be something like this:
cd ~/.mozilla/firefox/{random-string}/extensions/
The Firebug extension is identified by firebug#software.joehewitt.com.xpi. Create a new directory of the same name, but without the .xpi, and move the XPI into that directory:
mkdir firebug#software.joehewitt.com
mv firebug#software.joehewitt.com.xpi firebug#software.joehewitt.com
Next, change directories to your newly created Firebug directory, and unpack the extension:
cd firebug#software.joehewitt.com
unzip firebug#software.joehewitt.com.xpi
All of the files should be unpacked so that the extension's directories are in the current directory. Your file structure will look something like this:
$: ~/.mozilla/firefox/{random-string}/extensions/firebug#software.joehewitt.com$ l
chrome.manifest defaults/ firebug#software.joehewitt.com.xpi install.rdf locale/ skin/
content/ docs/ icons/ license.txt modules/
$: ~/.mozilla/firefox/ghlfe0bb.ff5.0/extensions/firebug#software.joehewitt.com$
Open consoleExposed.js in your text editor:
Next, change to the content/firebug/console directory:
cd content/firebug/console
Edit the consoleExposed.js file using your favorite editor:
vim consoleExposed.js
Disable console.timeStamp:
On or near line 215, you'll see the following function:
console.timeStamp = function(label)
{
label = label || "";
if (FBTrace.DBG_CONSOLE)
FBTrace.sysout("consoleExposed.timeStamp; " + label);
var now = new Date();
Firebug.NetMonitor.addTimeStamp(context, now.getTime(), label);
var formattedTime = now.getHours() + ":" + now.getMinutes() + ":" +
now.getSeconds() + "." + now.getMilliseconds();
return logFormatted([formattedTime, label], "timeStamp");
};
Right after the first curly-brace, force the function to return nothing:
console.timeStamp = function(label)
{ return ; // disable timestamp by returning
label = label || "";
if (FBTrace.DBG_CONSOLE)
Restart Firefox and enjoy a world without timeStamp:
After the edits, restart Firebug. You should no longer see the log messages for timeStamp in your console.
On the Development server, when using the ChannelAPI, it essentially degrades into a polling implementation instead of using Comet/long-polling. Thus, in your debugger, you see an endless stream of HTTP requests made to the server to continuously and methodically check for updates.
In essence, these are just AJAX requests, or as Firebug would like to think of them, XMLHttpRequests.
Since your browser is responsible for making these requests, the only way to disable them is to click the small arrow on "Console" in Firebug and uncheck the option for logging XMLHttpRequests.
Of course, this also disables logging for all of your other XMLHttpRequests. But it's a small price to pay for the clarity and serenity of a quiet, well-behaved JavaScript console.
For more helpful information on how to make the most of Firebug, see Firebug Tips and Tricks.
NOTE: This works for both users of the Python SDK as well as the Java SDK. (or Go SDK, assuming it has an equivalent ChannelAPI). This is not limited to only Python Appengine.
UPDATE:
From getFirebug:
Creates a time stamp, which can be used together with HTTP traffic timing to measure when a certain piece of code was executed.
The console.timeStamp method was released in Firebug 1.8.0. The same technique described above can also override this Firebug logging method.
console.timeStamp("This is the type of console logging statement that Google is using!");
The above logging statement would produce the olive text. This method can be disabled using the same techniques which were described in the previous section.
However, Google loads the console object inside of a closure, which means that, once Google's code is initialized, the ChannelAPI object has it's own copy of the console object.
In order to disable console.timeStamp, one would need to disable it as the very first action before anything else loads or runs. in other words, we would need to ensure that Google only gets its hands on the disabled console.timeStamp method.
For best results, load this code above the /_ah/channel/jsapi script tag to ensure the console.timeStamp method is disabled before jsapi loads:
if(window.console) console.timeStamp = function(t) { };
NOTE: Because Google invokes Firebug logging in this manner, the only solution may very well in fact require a bug report or feature request that would allow for programmatically disabling this level of logging. Alternatively, the Firebug team could provide a new version of Firebug that includes the ability to explicitly disable timeStamp log statements, similar to how they've done so with Errors, Warnings, XMLHttpRequests, and other log levels.

Any way to debug javascript on Android devices?

Are there any means of debugging JS code, or at least get errors, on Android devices?
This helps:
http://www.nanaze.com/2009/01/debugging-javascript-on-android.html
There are Firebug like methods (e.g. console.debug, console.info) that will log to logcat, so you can snoop there.
In my testing I'm getting logs to W/browser, not D/WebCore, but the info is being logged there.
Error messages should show up in the log with the WebCore tag.
Answered previously.
As it says http://www.technomancy.org/android/javascript-debugging/ you use can use console.log(...) to log messages, and then install a log viewer to view the logs if you filter based on browser (at least on Android 2.2)

What are some methods to debug Javascript inside of a UIWebView?

I'm trying to figure out why something with Javascript isn't working inside of a UIWebView. To my knowledge, there is no way to set a breakpoint inside of XCode for a js file. No problemo, I'll just go back to 2004 and use alert statemen-- oh wait they don't seem to work inside of a UIWebView either!
The only thing I could think of is by exporting my HTML And JS files to my desktop and then just doing my debugging inside of Safari. And that works! But of course, the bug I'm fighting with in the UIWebView doesn't occur in Safari.
Are there any other ways for debugging inside of a UIWebView, or any tricks that I can use akin to using the old-school alert method?
If you're using iOS >= 6 and you have mountain lion (10.8) or Safari >= 6, you can just:
Open the application in the simulator (or your device in XCode >= 4.5.x).
Open Safari (go to Preferences -> Advanced and make sure "Show Develop Menu in Menubar" is on.
From the Menu-bar (of Safari) select Develop -> iPhone Simulator -> [your webview page].
That's it !
This query tops google, so worth linking to the remoteInspector hidden in iOS5 - by far the best way found so far to debug your UIWebViews - just conditional compile out before you send to Apple.
alert() certainly works for me.
However, you can also do lots of other things, like make your own DHTML alert that pops up in a layer. This can be nice because you can do multiple alerts to a single div, without stopping your app. You should also be able to write a stack trace to it (the stack trace is in the exception object, and you can always throw your own exceptions).
Alternatively, if running on the simulator your custom "alert()" could call into objective C, and display the string in the iPhone simulator's console window:
document.location.href = "http://debugger/" +
encodeURIComponent(outputString);
and on the objective C side:
//--------------------------------------------------------------------
- (BOOL)webView:(UIWebView*)webView
shouldStartLoadWithRequest: (NSURLRequest*)req
navigationType:(UIWebViewNavigationType)navigationType {
if ([[[req URL] host] isEqualToString:#"debugger"]){
// do stuff with [[req URL] path]
}
}
That said, I have an app that is heavy on the UiWebView / javascript stuff, and I tend to do most javascript dev in Chrome (simulating what is necessary from the iPhone environment)
I get the awesome way to debug UIWebView Or
SFSafariViewController.
I hope It will Help.
Step 1:
Open Safari VC In Your Mac (hahaha Don't make your face, If I am saying in your Macbook just follow this my steps)

Step2: Go at Safari preferences And Click on Advance. 

You will Get this setting on your MacBook Screen.
Now enable the Show to develop menu in menu bar.

 Now Your All work is done. 

Are you thinking I am kidding :P :P no man...


Step3: Run your application in Device or Simulator. (Don’t Think Just run )
And go in your application where you are opening your Webview or SFSafariViewController.
Till now you did not understand I know. Be cool and see my next step.

Step4: Open Safari In your MacBook and Click on Develop Option from the Menu bar. 

Did you get something your MacBook, iPad/ iPhone is Displaying Right?????


Step5: Its Done. click your device and click on URL New popup will come out like This.



Step6: what are you looking now its over here all the steps.
Now debug your Webpage on this console.
Be happy and enjoy your day while doing coding With a cup of tea or
Coffee.
IMP: Don't forget to enable See Below Image








I haven't tried this yet, but take a look at this Weinre
Looks very promising.
This is an old question. But I'll still like to share my two cents.
I have been using jsconsole.com for remote debugging. It's easy. Just include a script tag and use console logs to debug by printing. This can also be used for debugging on a real device.
Old question, but I think I found the best solution, in my case you need to debug uiwebview, but I had no access to the IOS app and only to the html content and I had to view some JS logs, I added the following code to load the light firebug JS and show it automatically:
calling it from JS
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://getfirebug.com/firebug-lite-debug.js';
document.head.appendChild(script);
or load it from html
<script type="text/javascript" src="https://getfirebug.com/firebug-lite-debug.js"></script>
You can set up a system like that used in PhoneGap to send messages from JavaScript to Objective-C and log from there. In a nutshell, they are setting document.location with a custom scheme and blocking that scheme in the delegate callback.
You can take advantage of the fact that a UIWebView is most of the delegates for a WebView. WebKit is technically undocumented for iPhone, but mostly the same as specified in the desktop WebKit headers, possibly including the WebScriptObject. I use this for debugging, but be sure to strip this code out before submitting to Apple.
To get a WebView from a UIWebView, implement a delegate method like -(void) webView:(id)inWebView didFinishLoadForFrame:(id)inWebFrame in a subclass of UIWebView. Call super if you use that one.

Categories

Resources