Log JavaScript console into a log file with Firefox - javascript

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.

Related

Retrieving console errors to html

My question is different from the other posts similar to this.
AutoCAD offers developers a means of displaying a URL page inside the application. I created an intranet site for my company with the hopes that users can explore via desktop browser or their AutoCAD application.
The problem is that the browser AutoCAD uses is Chrome version 33 (currently its at 84) - there is no way to update or change the browser either.
I have no way to "inspect" or debug the site inside AutoCAD - and I've come to find out there are many difference in v84 and v33. I'm trying to diagnose errors right now but again, I have no way of accessing the console logs inside the AutoCAD Browser.
Is there a way for me to "alert" any errors that the console is trying to give me? (ie: the page can't find a script reference, there is an unexpected '.', etc...)
NOTE - my site runs great on the most updated Chrome browser (v84 on desktop browser), but some little things are not working right in v33 (in AutoCAD Browser).
If you control the website you can attach a listener on the window to listen for any unhandled exceptions. Add this before all other scripts to make sure everything is captured.
window.on('error', (e) => {
// if error is intresting, do work.
alert(e.message);
});
The handler accepts an ErrorEvent object.
NOTE - This will not capture errors that are triggered in scripts across domain. For example if you are loading google maps, and an error is triggered within that script, you will typically get a 'Script error.' and no other info. This has to do with cross origin policies. You can read more here.
If you need to specifically to capture data sent to console.error you can simply proxy the function. This may not capture anything except for code that explicitly calls console.error and is not recommended.
const error = console.error;
console.error = (...args) => {
// alert(...);
error.apply(console, args);
}

How to write file in Google Chrome App without prompting?

I am fumbling around with the free Chrome Dev Editor on my Chromebook. I am trying to use the fileSystem to read and write .txt files. It is all very wrapped up, not at all like in C. I can no more tell if I am even allowed to do something, let alone where the proper place is to find out how.
I think the files I can see using the Files thingy are in the sandbox that I am allowed to play in (meaning, folders that are accessible by the app?) The root is called Downloads. Sure enough, if I use all the dot calls and callback arguments for the read, as in the examples at developer.chrome.com/apps/filesystem, it works. But I have to have a prompt
every time for both reads and writes.
A little more Googling came up with this trick: (I think it was here in stackoverflow, in fact) a chrome.runtime call, getPackagedDirectoryEntry, that seems to give me a handle to the folder of my app. Great! That's all I need to not have to go through the prompting. For the readfile, anyway.
But then trying to apply the same trick to the writefile did not work. In fact, it did nothing discernible. No errors, no complaints. Nothing. Even though the write file with prompting works fine (so presumably I have the permissions and Blob construction right.) What to do?
Here is my code:
function test(){
// Samsung 303C Chromebook - Chrome Dev Editor - /Downloads/Daily/main.js
// prompted write
chrome.fileSystem.chooseEntry({type:'saveFile'},function(a){
a.createWriter(function(b){
b.write(new Blob(["Programming fun"],{type:'text/plain'}));
},function(e){trace.innerText = 'error is ' + e;});
});
// unprompted read
chrome.runtime.getPackageDirectoryEntry(function(a){
a.getFile('text.txt',{},function(b){
b.file(function(c){
var d = new FileReader();
d.onloadend = function(){trace.innerText = this.result;};
d.readAsText(c);
});
});
});
// unprompted write - why not?
chrome.runtime.getPackageDirectoryEntry(function(a){
a.getFile('new.txt',{create:true},function(b){
b.createWriter(function(c){
c.write(new Blob(["Miss Manners fan"],{type:'text/plain'}));
},function(e){trace.innerText = 'error is ' + e;});
});
});
}
To be fair, Filesystem API is a big mess of callbacks and it's not unreasonable to get drowned in it.
It's not currently documented, but chrome.runtime.getPackageDirectoryEntry returns a read-only DirectoryEntry, and there is no way to make it writable (it's specifically blacklisted).
You probably don't see an error, because it fails at the getFile stage, for which you don't have an error handler.
Unfortunately, for a Chrome App the only option to write out to a real filesystem is to prompt the user. However, you can retain the entry and ask only once.
If you don't need to write out to the real filesystem but need only internal storage, HTML Filesystem API can help you (yes, it's marked as abandoned, but Chrome maintains it since chrome.fileSystem is built on it).
Extensions additionally have access to chrome.downloads API that enables writing to (but not reading) the Downloads folder.
P.S. What you see in Files app is your "real" local filesystem in ChromeOS + mounted cloud filesystems (e.g. Google Drive)
You can use the basic web Filesystem API. First, add the "unlimitedStorage" permission. Then, copy the packaged files to the sandboxed filesystem, like this:
chrome.runtime.getPackageDirectoryEntry(function(package) {
package.getMetadata(function(metadata) {
webkitRequestFileSystem(PERSISTENT, metadata.size, function(filesystem) {
package.copyTo(filesystem.root)
})
})
})

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.

Store console logging in Chrome in a persistent way

In a school project I am running some javascript that are inputted through the console window and run from there. This script manipulates the web page and outputs the results to the console.
PROBLEM: Keep / save these results in a persistant manner that does not go away on browser close, script malfunctioning / page reload, or if possible, pc crash.
I thought of using frameworks such as Log4js or jStorage (jQuery Storage), but as this is not my website I'm manipulating, I can't add code or markup to the page.
Is there any way to do this?
NOTE: It is not critical that I log the results to console, I could send them off somewhere or do something else with them if that makes it more easy to log.
Thanks.
Here's a little function that stores logs into the WebStorage (persists across browser sessions):
console.plog = function () {
var key = Date.now();
var value = JSON.stringify([].slice.call(arguments));
localStorage.setItem(key, value);
console.log.apply(console, arguments);
}
To restore the logs, you'd have to run the following expression:
(function restoreLogs() {
var timestamps = Object.keys(localStorage).sort();
timestamps.forEach(function (ts) {
var logArgs = JSON.parse(localStorage.getItem(ts));
console.log.apply(console, logArgs);
});
}());
If you want to automatically save everything in Chrome Console you have to run Chrome with these options:
--enable-logging --v=1
It'll save the full log of chrome inside its data directory (note that the file will be overwritten on each run). More details here.
Alternative way: install the Sawbuck utility to manage Chrome logs.
Use console.error(arg); - it will send the console message into the browser's stderr (I'm pretty sure it will do so in the release builds, too.)
Start your browser from the command line and redirect your stderr into some file (something along the lines of chrome 2>errlog).

Trying to use nsIPrefBranch to store data on Firefox extension gives NS_ERROR_UNEXPECTED

I'm trying to save a small amount of persistent data in a Firefox extension.
So, I'm trying to use nsIPrefBranch like this:
var db = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
if(db.getCharPref('epoch')){ ///do something.. }
but it doesn't seem to work and I'm getting this error:
"Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED)
[nsIPrefBranch.getCharPref]"
Can somebody please tell what I'm doing wrong?
There is no preference called "epoch" - that's what this message is telling you. You have to set this preference before you can expect getCharPref() to succeed. Which is why extensions usually wrap calls to nsIPrefBranch into try .. catch blocks - errors are expected.
On a different note: preferences are a shared space (have a look at them under about:config). You should make clear that a preference belongs to your extension and make sure it won't conflict with preferences of other extensions or the browser. In other words, use something like "extensions.myExtension.epoch" rather than "epoch".

Categories

Resources