Solved

Calling java script from java applet

Posted on 2003-12-12
23
3,254 Views
Last Modified: 2013-11-23
Hi
Suppose this is my java program.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class testscript extends Applet
{
 Button btest;
 public void init()
  {
    try
      {
        btest=new Button("Test HjavaScript");
       }
      catch( Exception e){
      System.out.println(e);
       }
   }

public void start()
   {
}

public boolean handleEvent(Event e) {
      
            
       if((e.id==Event.ACTION_EVENT) ||(e.target==btest))//||(e.target==btest)))
       {
            String msg=new String("Hi Gaurav");
      }
}
}


this is my java script
<HTML>
<HEAD>


<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -


function MsgBox (textstring) {
alert (textstring) }


// - End of JavaScript - -->
</SCRIPT>


</HEAD>
</html>
How I will call java script function MsgBox from java applet program.I call this function on button click of the java program.

0
Comment
Question by:hansol1
  • 12
  • 11
23 Comments
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Add this method to your applet class:

  // Cool reflection based javascript calling method
  // Taken from http://www.rgagnon.com/javadetails/java-0172.html
  public String callBrowser( String jsCmd )
  {
    String jsResult = null ;
    boolean success = false ;
    try
    {
      Method getw = null, eval = null ;
      Object jswin = null ;

      /* does it in IE too */
      Class c = Class.forName( "netscape.javascript.JSObject" ) ;

      Method ms[] = c.getMethods() ;
      for( int i = 0 ; i < ms.length ; i++ )
      {
        if( ms[ i ].getName().equals( "getWindow" ) )
          getw = ms[ i ] ;
        else if( ms[ i ].getName().equals( "eval" ) )
          eval = ms[ i ] ;
      }

      Object a[] = new Object[ 1 ] ;

      a[ 0 ] = this ; /* this is the applet */
      jswin = getw.invoke( c, a ) ; /* this yields the JSObject */

      a[ 0 ] = jsCmd ;
      Object result = eval.invoke( jswin, a ) ;

      if( result instanceof String )
        jsResult = (String)result ;
      else
        jsResult = result.toString() ;

      success = true ;
    }
    catch( InvocationTargetException ite )
    {
      jsResult = "" + ite.getTargetException() ;
    }
    catch( Exception e )
    {
      jsResult = "" + e ;
    }

    if(success)
      return jsResult ;
    else
    {
      System.out.println( "eval failed with error " + jsResult ) ;
      return null ;
    }
  }

then, call the method with:

callBrowser( "MsgBox( '" + msg + "' )" ) ;

(make sure your applet is in the same HTML as the javascript

Tim
0
 

Author Comment

by:hansol1
Comment Utility
hi
program is not giving the alert message in internet explorer.I am using the first example give in the your link .
thanks
gaurav
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Post your applet source code, and your HTML (and any exceptions you are getting in the Java Console)

Tim
0
 

Author Comment

by:hansol1
Comment Utility
as i said you,i used the first example given in your link
////java code
import java.applet.*;
import java.net.*;

public class inJava extends Applet{
  public void init(){
    String msg = "We will jump to an HTML tag";
    try {
      getAppletContext().showDocument
        (new URL("javascript:doAlert(\"" + msg +"\")"));
      getAppletContext().showDocument
        (new URL("javascript:jumpTo(\"#JUMP\")"));
      }
    catch (MalformedURLException me) { }
    }
  }

//html page
HTML><HEAD></HEAD><BODY>
<SCRIPT>
function doAlert(s) {
   alert(s);
   }
function jumpTo(tag) {
   self.location=tag;
   }
</SCRIPT>
<APPLET CODE="inJava.class"
        NAME="myApplet"  MAYSCRIPT
        HEIGHT=400 WIDTH=10>
</APPLET>
<P>
<A NAME="JUMP">jump here from Java via Javascript</A><br>
</BODY>
</HTML>
 



Netscape AND Microsoft

thanks
0
 

Author Comment

by:hansol1
Comment Utility
hi
A java script function return type is String.how I handle that function in java apllet.
I try with this.
in java
line=getAppletContext().showDocument(new URL("javascript:setText(\"' +line+'\")"));
here line is of type String.in javascript it is like this.
function getText()
{
      return document.getElementById("UserText").value;
}
But it is giving error in java.How i get return value.
thanks
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
use the code I posted, not the first example from the link....that first example sucks :-(

-----------------

public class inJava extends Applet
{
  public void init()
  {
    System.out.println( callBrowser( "getText()" ) ) ;
  }

  public String callBrowser( String jsCmd )
  {
    String jsResult = null ;
    boolean success = false ;
    try
    {
      Method getw = null, eval = null ;
      Object jswin = null ;

      /* does it in IE too */
      Class c = Class.forName( "netscape.javascript.JSObject" ) ;

      Method ms[] = c.getMethods() ;
      for( int i = 0 ; i < ms.length ; i++ )
      {
        if( ms[ i ].getName().equals( "getWindow" ) )
          getw = ms[ i ] ;
        else if( ms[ i ].getName().equals( "eval" ) )
          eval = ms[ i ] ;
      }

      Object a[] = new Object[ 1 ] ;

      a[ 0 ] = this ; /* this is the applet */
      jswin = getw.invoke( c, a ) ; /* this yields the JSObject */

      a[ 0 ] = jsCmd ;
      Object result = eval.invoke( jswin, a ) ;

      if( result instanceof String )
        jsResult = (String)result ;
      else
        jsResult = result.toString() ;

      success = true ;
    }
    catch( InvocationTargetException ite )
    {
      jsResult = "" + ite.getTargetException() ;
    }
    catch( Exception e )
    {
      jsResult = "" + e ;
    }

    if(success)
      return jsResult ;
    else
    {
      System.out.println( "eval failed with error " + jsResult ) ;
      return null ;
    }
  }
}

-------------------

<HTML><HEAD></HEAD>
<BODY>
  <SCRIPT>
    function getText()
    {
         return document.getElementById("UserText").value;
    }
  </SCRIPT>
  <APPLET CODE="inJava.class"
                NAME="myApplet"  MAYSCRIPT
                HEIGHT=400 WIDTH=10>
  </APPLET>
  <br>
  <div id="UserText">Woo woo!!</div>
  <!-- div may be this...can't remember -->
  <div name="UserText">Woo woo!!</div>
</BODY>
</HTML>
0
 

Author Comment

by:hansol1
Comment Utility
hi tim
I am bit confused with callbrowser function.
I am not getting what is going on.
I make you clear that ,In javascript I have to function.In one function,I am passing one String argument and in another function I have to receive the String value.

function setText(myText)
{
      document.getElementById("TextEditor").innerHTML=document.getElementById("TextEditor").innerHTML+"<br>"+myText;
}

function getText()
{
      return document.getElementById("UserText").value;
}

how I will use these function in javascript.
what I get ,for returning function is that,inside callbrowser function you are receiving value in result.Is I am right?
Please  tim,try to understabd me.I don't know javascript.
thanks
0
 

Author Comment

by:hansol1
Comment Utility
hello TimYates

I get the callbrowser function.
what will i do for passing String value to the javascript.
function setText(myText)
{
     document.getElementById("TextEditor").innerHTML=document.getElementById("TextEditor").innerHTML+"<br>"+myText;
}
for the above function.
thanks
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
> what will i do for passing String value to the javascript.

callBrowser( "setText( 'some text' )" ) ;

:-)
0
 

Author Comment

by:hansol1
Comment Utility
TimYates
I have some problem.if you try to help me.I am not gettin about the callbrowser.Is it system defined  or user defined.PLease try to help me timYates.
I am posted here my full program with comments.Hope you will understand.
java file:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.Socket;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.TextField;

/*<applet code="support" width=450 height=260>
<param name=host value ="100.100.7.27">
<param name=port1 value="8888">
</applet>*/

public class Csupport extends Applet implements Runnable
{
    Button sendData;
    boolean  ClientStatusmsg;
   Thread t;
    byte[]linebuffer=new byte[3000];
   
   OutputStream opst,opstchat;
   String opratName;
    String outputData;
    String outputDatatemp;
   String msgconnect;
   InputStream   ipst;
   Socket  sock;
    String oprttyping;
    String host1,port1;
   int len;
   
  public void init()
  {
    try
      {
        sendData=new Button("Send");
                          
        add(sendData);
      sendData.setEnabled(false);
      ClientStatusmsg=false;
      host1=getParameter("host");
       port1=getParameter("port1");
      
      }
     catch(Exception e){
      System.out.println(e);
       }
   }

  public void start()
   {
    try
      {
      int port=8888;
      String sdg=new String();
      linebuffer = new byte[3000];
      System.out.println("Port Value Start" +port1);
      System.out.println("host Value Start" +host1);      
      sock=new Socket("100.100.7.27",8888);
      //sock=new Socket("65.61.162.30.",8888);
      opst =sock.getOutputStream();
          t = new Thread(this);
          t.start();
       sdg="CASE2001:^~%";
      sdg=sdg+host1 +"@#";
      System.out.println("Data from sdg"+ sdg);
        len=sdg.length();
          linebuffer=sdg.getBytes();
          if(len>linebuffer.length-1)
        len = linebuffer.length-1;
      opst.write(linebuffer, 0, len+1);
      opst.flush();
      }//end of try
      catch(Exception e) {
     //userChat.appendText("applet error: "+e+"\n");
    }//end of catch
  }//end of start function
   

//function to get input data
 public void run()
  {
      String temp = new String();
      String temp2=new String();
      String temp1;
      outputData=new String();
      outputDatatemp=new String();
      
      byte []buf1=new byte[3000];
       try
      {
      //ipst.reset();
       ipst = sock.getInputStream();
            byte[] buf = new byte[3000];
            while(true)
            {
               int avail = ipst.available();
                if(avail<1) avail=1;
                if(avail>buf.length)
                  {
                     avail=buf.length;
                  }

                  int bytes_read = ipst.read(buf,0,avail);
                  int j = 0;
                  int i;

                  for( i=0; i<=bytes_read; i++)
                  {
                         buf[j++] = buf[i];
                  }
                        
                  temp1 = new String(buf,0,0, j);
                  temp2 = temp2 + temp1;
                  temp2=temp2.trim();

                  System.out.println("temp1 :" +temp1);

                  if(j>bytes_read)
                  {
                        System.out.println("temp2="+temp2);
                        temp.trim();
                        System.out.println("temp :" +temp);
                        if(temp1.length()>3)
                        {
                              //int hh=temp1.indexOf (0,10);
                              outputData=temp1.substring(0,10);
                              outputDatatemp=temp2.substring(0,11);
                              System.out.println("outputData:" +outputData);
                              System.out.println("outputData:" +outputDatatemp);
                        //opratName.substring(
                              
                              
                  //Message when operator accept the chat

                        if((outputData.equals("ASE1007:~^"))||(outputDatatemp.equals("CASE1007:~^")))
                        {
                              String accp_msg=new String();
                              int pp=temp1.indexOf ("{",0);
                              String  tempoprtname=new String();
                              //pp=Integer.parseInt(output);
                              System.out.println(pp);
                              accp_msg=temp1.substring(10,pp-1);
                              int txtlen=accp_msg.length();
                              txtlen=txtlen+18;
                              int pp2=temp1.indexOf ("$",txtlen);
                              tempoprtname=temp1.substring(txtlen,pp2);
                              opratName=tempoprtname;
                              System.out.println("outputDataoperator name" + tempoprtname);
                              System.out.println("opratName name" + tempoprtname);
                              msgconnect=accp_msg +":" + tempoprtname;
                              System.out.println("Accept Message"+msgconnect);
                              try {
                                          getAppletContext().showDocument
                                      (new URL("javascript:setText(\"" + msgconnect+"\")"));
                                    System.out.println("Accept Message"+msgconnect);
                                          }
                                        catch (MalformedURLException me) {System.err.print(me); }
                                        
                              //dsend.setEnabled(true);
                                    sendData.setEnabled(true);
                                    //userText.setEditable(true);
                                    temp1=" ";
                                    outputData=" ";
                                    temp2=" ";
                                    msgconnect=" ";
                                    tempoprtname=" ";
                        }
                        
                        System.out.println("OutputData22" + outputData);

                        // start chattin
                        if((outputData.equals("ASE1011:~^"))||(outputDatatemp.equals("CASE1011:~^")))
                        {
                              String strTemp=new String();
                              String strColor=new String();
                              
                              System.out.println("temp1 in ASE1011"+ temp1);
                              
                              int pp=temp1.indexOf ("^",0);
                              int lp=temp1.length();
                              System.out.println("Value of P is "+pp);
                              strTemp=temp1.substring(pp+1,lp);
                              System.out.println("Chat data to send html"+strTemp);
                              //here I have to send strTemp data in javasript function
                              try {
                                          getAppletContext().showDocument
                                      (new URL("javascript:setText(\"" + strTemp+"\")"));
                                          System.out.println("Chat data to send html"+strTemp);
                                          }
                                        catch (MalformedURLException me) {System.err.print(me); }
                                        
                              //strTemp="";
                              temp1="";
                              outputData="";
                              temp2="";
                              strTemp="";
                        }
                        
                        
                  }//end of temp length if
                  }//end of outer if
                  }//END OF WHILE
            
            //System.out.println("TempValue:"+temp);
        
      } catch(Exception e) {

           System.err.print(e);
    }
  }
      
 


/////////////////////////////////////////////////////////////
//handle mouse event to click on button
      
      public boolean handleEvent(Event e) {
      
            
       if((e.id==Event.ACTION_EVENT) && (e.target==sendData))//||(e.target==userText)))
       {
            
            byte[]linebuffer=new byte[3000];
            String ClientChat="CASE2002:^~#%";
            String line =new String();//= getText;
//here I have to receive the value.
            /*try {
                  //line=getAppletContext().showDocument(new URL("javascript:setText(\"' +line+'\")"));
                  }
                catch (MalformedURLException me) {System.err.print(me);}*/
                if(line.length()>0)
                {
            System.out.println("Value of line " +line);
            line=port1+": "+line;
            ClientChat=new String(ClientChat+opratName+"~!"+host1+"~!"+line+"{}") ;
            
            System.out.println("Value to send"+ClientChat);
            //userChat.appendText(">>"+line+"\n");
            System.out.println("Value to sendcheck exception"+ ClientChat);
             int len = ClientChat.length();
            linebuffer=ClientChat.getBytes();
            
            if(len>linebuffer.length-1)
            len = linebuffer.length-1;
            linebuffer[len]='\n';
            System.out.println("Hello");
            try {
                  //opst=sock.getOutputStream();
                  System.out.println("in trytest");
                    opst.write(linebuffer, 0, len);
                  opst.flush();
                  } catch(Exception ex) {

              System.err.print(ex);
      
                  }
            
            //userText.setText("");
            ClientChat=" ";      
            line="";
          }//end of String length if
            }//end of if
      
            return false;
       }//end of function
}
      //trap cursor foucs
      
  Please Tim try to help me.
thanks



                     



                   
0
 

Author Comment

by:hansol1
Comment Utility
I am gettin this error for gettext function.
java.net.MalformedURLException: unknown protocol: javascriptOutputData22
eval failed with error== netscape.javascript.JSException: MAYSCRIPT is not enabled for this applet
null
eval failed with error== netscape.javascript.JSException: MAYSCRIPT is not enabled for this applet
null
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 35

Expert Comment

by:TimYates
Comment Utility
> eval failed with error== netscape.javascript.JSException: MAYSCRIPT is not enabled for this applet

MAKE SURE  you have "MAYSCRIPT" in your applet tag:

<APPLET CODE="inJava.class" NAME="myApplet" HEIGHT="400" WIDTH="10" MAYSCRIPT></APPLET>

You did before...have you taken it out?
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
> I am not gettin about the callbrowser.Is it system defined  or user defined.

It is a method...  put it in your main Csupport Applet class  like I did in my "inJava" example...

Tim

0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
the callBrowser function just uses reflection to call a piece of javascript in the same HTML as the applet :-)

You can do it without reflection, but then you need to add java40.jar to the classpath when you compile, as the compiler will not be able to find the JSObject class otherwise...

That's why it's easier to use reflection :-)

Tim
0
 

Author Comment

by:hansol1
Comment Utility
java.net.MalformedURLException: unknown protocol: javascript
getting this error
Please give me for both function.String return type with argument and void reurn type with String argument.
0
 
LVL 35

Accepted Solution

by:
TimYates earned 100 total points
Comment Utility
>  java.net.MalformedURLException: unknown protocol: javascript

What are you doing?  That's not an error from my code...

are you still doing showDocument() ?

Get rid of it...

Just use callBrowser()...

CHANGE:
-----------------

                         try {
                                    getAppletContext().showDocument
                                 (new URL("javascript:setText(\"" + msgconnect+"\")"));
                              System.out.println("Accept Message"+msgconnect);
                                    }
                                  catch (MalformedURLException me) {System.err.print(me); }
                                 

TO
-----------------

                         callBrowser( "setText( '" + msgconnect + "' )" ) ;

(make sure you have added the callBrowser method to your applet class)

Tim
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
> Please give me for both function.String return type with argument and void reurn type with String argument.

I have shown you twice already...

void return type, string argument:
---------------------------------------
callBrowser( "setText( 'Hello' )" ) ;

string return type, string argument:
---------------------------------------
String s = callBrowser( "getText( 'Hello' )" ) ;

string return type, no argument:
---------------------------------------
String s = callBrowser( "getText()" ) ;

0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
The callBrowser method (again) that you need to add to your applet class is:

--------------------------------

public String callBrowser( String jsCmd )
  {
    String jsResult = null ;
    boolean success = false ;
    try
    {
      Method getw = null, eval = null ;
      Object jswin = null ;

      /* does it in IE too */
      Class c = Class.forName( "netscape.javascript.JSObject" ) ;

      Method ms[] = c.getMethods() ;
      for( int i = 0 ; i < ms.length ; i++ )
      {
        if( ms[ i ].getName().equals( "getWindow" ) )
          getw = ms[ i ] ;
        else if( ms[ i ].getName().equals( "eval" ) )
          eval = ms[ i ] ;
      }

      Object a[] = new Object[ 1 ] ;

      a[ 0 ] = this ; /* this is the applet */
      jswin = getw.invoke( c, a ) ; /* this yields the JSObject */

      a[ 0 ] = jsCmd ;
      Object result = eval.invoke( jswin, a ) ;

      if( result instanceof String )
        jsResult = (String)result ;
      else
        jsResult = result.toString() ;

      success = true ;
    }
    catch( InvocationTargetException ite )
    {
      jsResult = "" + ite.getTargetException() ;
    }
    catch( Exception e )
    {
      jsResult = "" + e ;
    }

    if(success)
      return jsResult ;
    else
    {
      System.out.println( "eval failed with error " + jsResult ) ;
      return null ;
    }
  }
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
AND make sure you have put MAYSCRIPT in the applet tag on the HTML page
0
 

Author Comment

by:hansol1
Comment Utility
Thanks a lot tim.Please help once again.
the return value I am not gettin g.It is giving undefined.I am using in this way.
in java
String d=new String();      
          d=( callBrowser( "getText()" ) ) ;
      System.out.println("return value"+d);
in java script
function getText()
    {
      var s = "PP";
         return s;
    }
other call browser function is the same.I am getting the result of  void return type, string argument:
One more thing Tim,when ever I change in java file,i doesn't reflect on html file,until I recompile java file in different name .why this problem occur.I am using IE5.
Thanks.Once again.
0
 

Author Comment

by:hansol1
Comment Utility
Why this error is coming
eval failed with error== com.ms.com.ComFailException: Could not complete the operation due to error 80020101.
thanks
0
 

Author Comment

by:hansol1
Comment Utility
PLease help me on my lasr two comment
0
 

Author Comment

by:hansol1
Comment Utility
I failed to get return value from java script.Please refer my third last comment.It is returning a String "Undefined"
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This video teaches viewers about errors in exception handling.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now