Majiy
Majiy

Reputation: 1920

Can a Java Applicaton and a JavaScript running in a browser communicate with each other?

I have a JavaScript embedded in a website, running in a normal browser, and I have a Java Application running on the same machine. I am looking for a way have both communicate with each other.

I assume that creating files in the local file system from inside JavaScript running in a browser is out of question.

The only way I came up with would be to use a server that both programs can send messages to, and from which they poll for new messages.

Is there any other other way to accomplish this?

Upvotes: 3

Views: 1490

Answers (3)

lexicore
lexicore

Reputation: 43671

A couple of ways I saw in practice:

  • You Java Application may listen to some local port which your JS will access for instance via XHR. You'll need to mind cross-site scripting (your JS may need to be loaded from that local URL), but this is doable. The easiest would probably be to run an embedded HTTP server.
  • Your Java Application may be registered as a protocoll handler in the OS. Then JS would open links registered with the application thus sending data to it.

As @PavelHoral is pointing out, CORS is a way to workaround same-origin policy.

Upvotes: 3

geert3
geert3

Reputation: 7331

Please refer to this question for direct sockets communications from within javascript. You'll need a HTML5 browser, and likely this won't "just" work or necessarily be a good idea if you want to publish this on the WWW.

How to Use Sockets in JavaScript\HTML?

Upvotes: 0

Pavel Horal
Pavel Horal

Reputation: 18194

JavaScript inside a browser can only make AJAX requests or communicate with browser plugins if they provide some additional JS interface.

Local HTTP connection

One option is to listen for HTTP connections in your Java application (does not have to be servlet).

You will need to handle CORS correctly.

Central server

Other option is to have a central server to which both your JS and Java code will connect.

Java applet

Another option is to have Java applet. When running in privileged mode you can do pretty much anything (maybe you can convert your Java application to Java applet).

You will need to handle applet security here (e.g. signing applet with trusted certificate).

Upvotes: 1

Related Questions