how to attach debugger to device? chrome extention - javascript

This is the code from my chrome extension, as far as i am aware it should return all targets that i can attach a debugger to:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('launching extention');
chrome.debugger.getTargets(function(result){
console.log('Result!');
console.log("count: "+result.length);
for (index = 0; index < result.length; index++) {
console.log(index+": "+result[index].url);
}
});
});
This is my console output from the above extension:
This shows only tabs open in the chrome browser returned as debuggable targets.
I have my device connected and setup correctly so i can debug android chrome tabs.
Is the method i am using to try to attach to the devices debugger correct?
Related Docs Links;
remote-debugging, debugger, debugger-protocol, debugging-clients.

Whoops. Seems like this API does not allow to attach to device pages. Worse, I can't find any feature requests to enable it to do so.
Therefore, you will need to go low-level, and use the "legacy workflow" to expose the debugger for raw access on the phone you're connecting.
Essentially, the important part is running ADB command
adb forward tcp:9222 localabstract:chrome_devtools_remote
that exposes the debugging interface of Android Chrome at localhost:9222, after which you can use XHR / WebSockets to relay raw protocol messages.
I'm afraid that's the only way; if you need the ADB step to be done automatically, you can use a Native Host script. Note that you still can't bypass the "pairing" part that needs to be done on the phone.

Related

$window.location = pdfLocation; not downloading PDF AngularJs

I am receiving the location of a pdf document in angular, and I cant get it to consistently download.
It works on my home laptop, but not whilst at work.
Code below
RenderService.document('document.pdf', spec).then(function(pdfLocation) {
$window.location = pdfLocation;
});
Works in Chrome on Ubuntu at home, not on the same set up at work. Does anyone know any reason why the operation of '$window.location' wouldn't be idempotent?
Update:
Also works on FF on my work machine, just not Chrome
This mostly happends if you have some third part software installed or the browser security is configured as to high. Check for addblocker & antivir software on your machine and also check the security configuration in your browser. Ensure that your pdf location is based on HTTPS if your application is running on HTTPS.
For Chrome & Safari try to set your window.location.href property instead of window.location. This should work for all browser so.
RenderService.document('document.pdf', spec).then(function(pdfLocation) {
window.location.href = pdfLocation;
return false;
});
Here is a plnkr demo which does run well in chrome.
Thanks to #lin I realised the issue was chrome blocking my download due to the advanced security option in Chrome:
"Protect you and your device from dangerous sites"
I'm not sure how to get around it yet, and will update this answer if I find a solution

Avoid the detection of "whether Chrome DevTools(console) is open"

Today I see this post
Find out whether Chrome console is open .
#zswang gave the way to detect if Chrome DevTools(console) is open. That's really suprise me, then I began to think is there any way to walk around this detection technique?
There are two way to detect chrome DevTools is open(detail in above post)
Using Object.defineProperty
I can walk around this, it can be assign to another function.I have tried Object.defineProperty=null ,then the detect function die(I know write a mock function is better, here just an example)
Using obj.__defineGetter__ (Object.prototype.__defineGetter__)
Object.prototype.__defineGetter__= null would not break the detection, how to walk around?
Finally, I have to say I don't like to be monitored.Hope there is a proper way to walk around.
There are so many ways to detect the use of DevTools, that it would be difficult to block them all. As DevTools gains new features, there are new ways to detect its use. Any third-party tool to block detection can't be trusted to block 100% of detection techniques.
There is a bug reported to the Chromium team here on the idea of integrating detection blocking directly into Chrome.
Disable javascript
The only way to definitively block any detection of the use of DevTools is to disable javascript. You can still execute javascript in the DevTools console when javascript for a page is disabled. I have found it sufficient to disable javascript immediately after opening DevTools, like this:
Open DevTools Command+Option+J (Mac) or Control+Shift+J (Windows, Linux)
Type the hotkey to open the command menu – Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows, Linux)
Type dis and hit return to select the Disable Javascript option.
… inspect the website …
Re-enable javascript by evoking the command menu and typing ena and hit return (selecting the Enable Javascript option)
Of course, this method is useless for monitoring malicious code because no code is running when javascript is disabled. But at least it may give you a chance to set breakpoints before re-enabling javascript.
Chrome DevTools Protocol
It may be possible to use the Chrome DevTools Protocol to connect to a separate instance of Chrome and inspect a website without opening DevTools in that instance at all:
The Developer Tools front-end can attach to a remotely running Chrome instance for debugging. For this scenario to work, you should start your host Chrome instance with the remote-debugging-port command line switch:
chrome.exe --remote-debugging-port=9222
Then you can start a separate client Chrome instance, using a distinct user profile:
chrome.exe --user-data-dir=<some directory>
Now you can navigate to the given port from your client and attach to any of the discovered tabs for debugging: http://localhost:9222
The most popular method of detecting if dev tools is open involves invoking console.log() which happens only when devtools is opened.
Below is an example:
var image = new Image();
Object.defineProperty(image, 'id', {
get: function() {
$('#<element_to_remove_on_detection>').remove();
console.clear();
}
});
console.log('%c', image);
In the above case, a new image object is created and the getter is overridden for the 'id'. When console.log is invoked, the getter is called as well.
So basically, any time the getter is called, the website knows that the devtools has been opened because console.log() doesn't get called until devtools is open.
It is a really clever way of detection. Nonetheless, when trying to debug such code, Simply using extension like Resource Override and injecting
console.log = null;
Into the head of the page should stop the website from detecting if devtools is open.
For me, I just added a breakpoint at the top of the offending script, then ran Image = null in the developer console.
I found this solution by googling how websites do that, which brought me this stackoverflow post, I could see in my console a new Image was being logged, so setting Image to null causes an error, which causes the detection to fail.
You could try something like this:
var oldDefineProperty = Object.defineProperty;
Object.defineProperty = function() {
var firstArg = arguments[0];
arguments[0] = _.extend({
get id() {
return firstArg.id;
}
}, arguments[0]);
return oldDefineProperty.apply(this, arguments);
}
var element = new Image();
element.id = "something";
Object.defineProperty(element, 'id', {
get: function() {
alert("detected");
}
});
console.log('%cHello', element);
<script src="http://underscorejs.org/underscore-min.js"></script>
This seems to prevent the alert from showing for me. I'm using the _extend function from Underscore. I don't know if I'm missing anything but just playing around.
As for __defineGetter__, this was deprecated so you'd expect this not to be used.

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

WebSocket supported in Android Stock Browser or not?

using https://github.com/einaros/ws
Server:
var WebSocketServer=require('ws').Server,wss=new WebSocketServer({port:8004});
wss.on('connection',function(s) {
s.on('message',function(_){console.log('received: '+_);});
});
Client:
var s=new WebSocket('ws://mysite.com:8004');
//android default browser dies here <---------------?
s.onopen=function(){
$('body').css({'background':'green'});
s.send('hi');
};
I have to ask why android default browser does not open the connection?
I visit www.websocket.org/echo.html on the default android browser and it says This browser supports websocket. so what is the problem?
This simple code works on iphone safari, windows chrome, android mobile chrome no problem.
On android default browser I can also console.dir(window.WebSocket); and it shows the WebSocket Object no differently than other browsers.
If someone knows why, please tell.
Thanks
UPDATE
if (!window.WebSocket && window.MozWebSocket) {
window.WebSocket = window.MozWebSocket;
alert('MozWebSocket');
}
else if (!window.WebSocket) {
alert("WebSocket not supported by this browser");
}
else{
alert('wtf!? '+window.WebSocket);
}
This gives me a console log of:
wtf!? function WebSocket(){[native code]}
The Android stock browser does not, in fact, support WebSocket.
Some work was apparently done in preparation for adding support, so the API in the browser is there, i.e. you can create a WebSocket object. It's just that this doesn't actually do anything behind the scenes.
This results in a simple feature support check, which just attempts to create the socket object, showing WebSocket support. Check the readyState for a created WebSocket object instead, and you'll see that this never changes from "0".
Starting with Android 4.4, there is no stock browser anymore. The Web view component has been switched to Chrome for Android - and this does support WebSocket.

Log JavaScript console into a log file with Firefox

We have a web application which runs in a kiosk mode Firefox, using the RKiosk extension to achieve this. We suspect that we have a very rare error in the system which yields in a JavaScript error. However because we can't access the JavaScript console we can't examine the log.
I'm searching for an option to make Firefox log all JavaScript console messages into a file regardless of the tab and page opened. I can't seem to find any extension for this. I'm already using log4javascript which sends errors back to the server, but it seems that our application crashes in a way that it skips the logging altogether.
Writing to a file sounds like a tedious task to me. It requires privileges that browser code doesn't normally have and you'd have to negotiate with an add-on you'd have to write in order to access file I/O.
From what I understand your issue is
I'd like to make Firefox log all errors
There are several approaches we can do to tackle this
First approach - log everything to localStorage too:
Now, rather than writing to an actual file, you can write to localStorage or IndexedDB instead.
localStorage["myApplog"] = localStorage["myApplog"] || "";
var oldLog = console.log;
console.log = function(){
oldLog.apply(console,arguments); // use the old console log
var message = "\n "+(new Date).toISOString() + " :: "+
Array.prototype.join.call(arguments," , "); // the arguments
localStorage["myApplog"] += message;
}
This is rather dirty and rather slow, but it should get the job done and you can access the log later in local storage. LocalStorage has a ~5MB limit if I recall correctly which I think is enough if you don't go crazy with logging. You can also run it selectively.
Second approach - log only errors
This is similar to what Pumbaa80 suggested. You can simply override window.onerror and only log errors.
// put an empty string in loggedWinErrors first
var oldError = window.onerror || function(){};
window.onerror = function(err,url,lineNumber){
oldError.call(this,err,url,lineNumber);
var err ="\n Error: (file: " + url+", error: "+err+", lineNumber: "+lineNumber+")");
localStorage["loggedWinErrors"] += err;
}
Third and drastic approach - use a VM.
This is the most powerful version, but it provides the most problematic user experience. You run the kiosk in a virtual machine, you detect an uncaught exception - when you do you freeze the machine and save its state, and run a backup VM instead. I've only had to do this when tackling the most fearsome errors and it's not pretty. Unless you really want the whole captured state - don't do this.
Really, do the extension before this - this is tedious but it gets very solid results.
In conclusion, I think the first approach or even just the second one are more than enough for what you need. localStorage is an abstracted storage that web pages get for saving state without security issues. If that's not big enough we can talk about an IndexedDB solution.
It all really depends on the use case you have.
You can use XULRunner...a Mozilla runtime environment for XUL applications. It uses Gecko like Firefox and:
You can access the file system or using the SQLite database to store logs.
You can render your kiosk in fullscreen mode without using extensions.
Have you tried jserrorcollector? We are using it and it works fine (only in Firefox). It's only for Java.
// Initialize
FirefoxProfile ffProfile = null;
ffProfile = new FirefoxProfile();
JavaScriptError.addExtension(ffProfile);
// Get the errors
List<JavaScriptError> jsErrors = JavaScriptError.readErrors(webDriver);
More information: https://github.com/mguillem/JSErrorCollector
Have you considered remote logging?
I commonly assign window.onerror to do send a request to a webserver storing the details of the error remotely. You could do the same with console.log if you preferred.
Try the following console export. It is a plugin for Firebug of Firefox. It's quite handy.
http://www.softwareishard.com/blog/consoleexport/
If you are able/willing to switch from Firefox to Chrome or Opera you would be able to use the Sandboxed Filesystem API to write a local file. See:
http://www.html5rocks.com/en/tutorials/file/filesystem/
http://caniuse.com/filesystem
Start in kiosk mode using chrome.exe --kiosk <url>
You would then want to disable Alt-F4 and Ctrl-Alt-Del which on Windows can be done with several third-party tools like Auto Hotkey (Disable Ctrl-Alt-Del Script).
You could use a remote logging script like Qbaka. It catches every JS error and sends it to the Qbaka server. There you can login and see all JS errors. Qbaka stores the exact error message, the script, line number, stack trace and the used browser for each error message.

Categories

Resources