NovelProjects

Monday, March 16, 2009

Java JSObject and Safari

I felt pretty good about my Java to Javascript communication after my last post, but a new problem arised. Now, I've never really had a direct issue with Safari. Most of the time any errors you see on Safari are just syntax errors which aren't handled as graciously as FireFox or other browsers. But, this is in fact a Safari issue that I came across.



The issue is that I want to pass a couple arrays of data from Java to Javascript. My previous Java code was something like this:



protected void sendToJS(File[] files)
{
String[] names = new String[files.length];
String[] paths = new String[files.length];

for (int i=0; i<files.length; i++)
{
names[i] = files[i].getName();
paths[i] = files[i].getAbsolutePath();
}

JSObject.getWindow(this).call("newfiles", new Object[]{names,paths});
}


This seemed to work just fine, until I got to Safari. For some reason, you can't seem to pass arrays to Javascript. I tried making a static array and passing that to Javascript - no dice. Pretty frustrating, actually. I was running through my head if it was a permission error, certificate error, or for some reason an actual hurdle that I couldn't overcome.



So, what's the solution?



The solution is to format everything in JSON and let Javascript parse that for you. It's not as convenient, but it was the only way to let Javascript have the format it needed for every browser. Here's an example of what the JSON should look like for my example:



"['file1','file2','file3']"


The Javascript needed to parse this so you can actually loop through it isn't that bad at all. Javascript has a built-in function eval which will take the JSON and make it into an object that you can work with.



function newfiles(arg1, arg2){
var names = eval("(" + arg1 + ")");
var paths = eval("(" + arg2 + ")");

// do you looping with names.length or access directly with names[1]
}


Again, annoying, but at least it's a solution.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.