Thursday, March 31, 2011

JavaScript notes: an Applet puzzle

This one has driven me a little crazy over the last few hours.

As part of my learning about JavaScript and HTML5 I thought I would try embedding an applet in an HTML5 page. Which I could easily do. Then I made the applet record a sound and then replay it. To do this the applet needs to be signed. So no problem, I used a self signed certificate, loaded my applet and everything just worked. Sweet.

The next thing I then tried to do was to get the JavaScript on the web page to call into the applet.
 <input type="button" value="record" onClick="document.getElementById('recorderApplet').doRecord();">

Hacky - In my defense, I was just trying to see if I could get the call to work...

When I pressed the HTML button in my browser:
POW!: access denied (javax.sound.sampled.AudioPermission record)

This was a little unexpected - if the applet button was pressed, I recorded. If the HTML button was pressed, then I got a security error.

I Googled the world and found Bug 4406607 and Mozilla bug 60120
But somehow the answers within didn't seem satisfactory.
Then my searches hit gold: Java Access Control Mechanisms (pdf)

A very nice explanation of what was happening, with a simple answer: change my Java method that was being called by the JavaScript to the following:

public String doRecord() {
        return AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return "recording started";

Now my applet records when I hit the HTML button. Sweet.

No comments: