Read local file in Phonegap - javascript

I'm trying to read a local file in Phonegap to load the language strings for the application and I can't make it work :(
The code is pretty straightforward:
var pathToLocalFile = "/home/user/android/assets/www/js/";
var langCache = new FileReader();
langCache.onload = function(data){
col = JSON.parse(data);
refreshAllStrings();
};
langCache.onerror = function(err){
debug.error(err);
};
langCache.readAsText(pathToLocalFile+currentLang+'.json');
This code doesn't work on the Ripple emulator and I replaced it with
var pathToLocalFile = "file:///android_asset/www/js/";
in case of android, with the same result:
Uncaught TypeError: Object #<Console> has no method 'warning' cordova-2.4.0.js:2616
initRead cordova-2.4.0.js:2616
FileReader.readAsText cordova-2.4.0.js:2660
loadLanguage
In the Ripple emulator, I started Chrome with google-chrome -–allow-file-access-from-files and the Android config and manifest has all the permissions for and the plugins set.
Of course I'm missing something, but any idea what this could be?
Regards.

If the file is under the www folder of your app you don't need to add '/home/..' or 'file:///'. You should just be able to load the contents using an "AJAX" fetch even though it is bundled in the app.
$.get('js/filename.ext');

The error you're seeing is actually a result of cordova-2.4.0.js calling a non-existent "warning" method. It should be console.warn. It is attempting to warn you that using a string for the readAsText method is now deprecated, and that you should use a File reference instead.
What should be happening is a console.warn of "Using a string argument with FileReader.readAs functions is deprecated."

Related

Crossrider external js file not loading :PDFJS is not defined

Below are my codes in extension.js. If you look at the codes, I tried different ways to load the file to my extension. No matter what, I always getting
VM3051:15 Uncaught ReferenceError: PDFJS is not defined
Tried with putting the file in different locations.
appAPI.ready(function($) {
console.log("pdf min js loading");
appAPI.resources.includeJS('jspdf.js');
// appAPI.resources.includeJS('js/jspdf.js');
// appAPI.resources.includeRemoteJS('//cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js');
//$.globalEval(appAPI.resources.get('//cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js'));
console.log("done");
setTimeout(function(){
alert(window.location.href);
if(window.location.href.indexOf(".pdf") > -1) {
console.log("its a pdf");
alert("pdf");
var doc = new jsPDF();
}else{
alert($.trim($('div').find('h1,h2,h3,h4,h5,p,span').text()));
}
},6000);
});
Here is the file structure
I cannot modify manifest.json because the extension should be unique for all the browsers not just for chrome.
I'm confused, the two CloudFlare URLs in your code reference the project jsPDF. I would assume the local pdf.js does the same too.
In your code, you're using
PDFJS.getDocument();
This syntax comes from PDF.js which is a totally different project from Mozilla.
If you're sticking with jsPDF, your code should be something like:
var doc = new jsPDF();
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');
Or you'll need to include the correct library for PDF.js.
After the edits you've made and your comments, it seems you've switch completely over to jsPDF but you're still getting the same error which clearly mentions PDF.js.
Are you sure you're debugging the correct and last version of your app which is only using jsPDF?
I've setup a small reproduction example on Crossrider using only jsPDF.
The extension.js code is the following:
appAPI.ready(function($) {
console.log("pdf min js loading");
appAPI.resources.includeJS('jspdf.js');
console.log("done");
var doc = new jsPDF();
console.log(doc);
});
When debugging the extension, I'm getting this result:
doc is an object containing an instance of jsPDF which I can later use.
There should be no mention of PDF.js whatsoever. My only guess could be that you're running / debugging a version of your extension still containing references to this project.

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

Objective-c Warning for the webview of a dropbox plugin

Warning recieved : WebKit discarded an uncaught exception in the webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame: delegate: The view passed in does not have a window.
dropbox plugin method for getting the files from dropbox inside it i have created an array to get the files and send it to javascript to display the output
getfiles:-
jscallback=[NSString stringWithFormat:#"getFilename(%#)",dropBoxArray];
[self writeJavascript:jscallback];
Method defined in javascript
window.getFilename=function(str)
{
alert(str);
cordova.exec(linkDropboxCB, linkDropboxFail,"DropboxPlugin","getfiles", [""]);
}
getfiles is the method in the dropbox plugin,which contains the above code.
Please help me to remove the warning.

Web worker: NotFoundError when I try to read a file created in the main thread

In Chrome 32, I've got an JS app where I write raw images from a canvas to a file and I want to close the file and open it for processing in a worker.
I pass the file name to the worker and I can see that it's found and opened but as soon as I try to read it I get a DOM exception (NotFoundError).
// In my worker:
fs = self.requestFileSystemSync(self.PERSISTENT, quota);
var f = fs.root.getFile(rawFileName, {create: false}); // this works, f is valid
var reader = new FileReaderSync();
// At this point, 'reader' looks ok
rawFramesArrayBuffer = reader.readAsArrayBuffer(f); // My exception is thrown here.
log("Opened " + rawFileName + " for reading.");
In my main thread, I've tried setting my File and FileWriter to undefined to ensure the file is closed (I can't see a method for doing this), but it doesn't help. In any event, the spec says that a NotReadableError should be thrown if the file is locked, but I don't see this.
If I step through the code, everything pauses for about 5 seconds when I step over the readAsArrayBuffer line and then the NotFoundError is thrown.
If I create a DirectoryReader and enumerate all the files, I can see that my file exists.
You may want to pass the images to the worker rather than saving them and having the worker open a file.
Here is a page with sample code
http://kinderas.blogspot.com/2011/06/html-5-web-workers-and-image-processing.html
But it does depend on how big your image is.
I found this interesting but haven't tried to do processing from the computer camera so it may help you out.
http://blog.aviary.com/posts/live-image-processing-with-getusermedia-and-web-workers
I needed to access the file via the FileEntry:
rawFramesArrayBuffer = reader.readAsArrayBuffer(f.file());

Launch local executable from greasemonkey

Below is the code I am trying (plus a few variations), there is a dialog asking for my permission, but still errors out with
Error: Permission denied for to get property XPCComponents.classes
unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var file = unsafeWindow.Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("d:\\test.bat");
var process = unsafeWindow.Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(file);
var args = ["argument1", "argument2"];
process.run(false, args, args.length);
Is this just going to be impossible?
#Jano answer is right, but you can still invoke the .bat file using a custom protocol handler such as myprotocol://parameters. Also explained here: How to run local program (exe) via Chrome via HTML/javascript
Adding this keys to your registry:
HKEY_CLASSES_ROOT
myprotocol
(Default) = "URL:Test Protocol"
URL Protocol = ""
shell
open
command
(Default) = "d:\test.bat" "%1"
And inside the .bat to capture the parameter:
set param=%1
echo Parameter is "%param:~13,100%
Where :~13,100 Crops the first 13 characters of the parameter (myprotocol://)
Then in your script just use the custom protocol URL on window.location, $.ajax or assign to an <a>'s href.
You can't. See Do Greasemonkey scripts have chrome privileges?.

Categories

Resources