views:

1230

answers:

2

Hey guys.

I read that you could call JavaScript code from a Java Applet by calling

JApplet.getAppletContext().showDocument( "javascript:alert('Hello World');" );

However, when I do this i get the following error:

java.net.MalformedURLException: unknown protocol: javascript

How do I work around this?

+1  A: 
 try {
  this.getAppletContext().showDocument(new URL("javascript:alert('hello world');"));
 }catch(Exception e) {
  e.printStackTrace();
 }

Works !!

Maybe the browser does not have javascript enabled.. just a guess

Satish Motwani
+2  A: 

Hi,

I get the same exception as you do because of that the URL class does not accept javascript: as a valid protocol.

There is a workaround though; supply an URLStreamHandler to the URL constructor.

Example:

final URLStreamHandler streamHandler = new URLStreamHandler() {

    @Override
    protected URLConnection openConnection(URL u)
        throws IOException {
        return null;
    }

};

try {
    getAppletContext().showDocument(
        new URL(null, "javascript:alert('It works!');", streamHandler));
} catch (MalformedURLException me) {
    //log or whatever
}
This opens a new tab in Firefox, but the page and location address are both empty. Nothing happens.. :/
Nevermind, apparently my Firefox 3.0.3 on Ubuntu is bugged :) It works perfectly on other computers. Thanks!