Calling java script from java applet

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.

hansol1Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TimYatesCommented:
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
hansol1Author Commented:
hi
program is not giving the alert message in internet explorer.I am using the first example give in the your link .
thanks
gaurav
TimYatesCommented:
Post your applet source code, and your HTML (and any exceptions you are getting in the Java Console)

Tim
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

hansol1Author Commented:
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
hansol1Author Commented:
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
TimYatesCommented:
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>
hansol1Author Commented:
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
hansol1Author Commented:
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
TimYatesCommented:
> what will i do for passing String value to the javascript.

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

:-)
hansol1Author Commented:
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



                     



                   
hansol1Author Commented:
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
TimYatesCommented:
> 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?
TimYatesCommented:
> 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

TimYatesCommented:
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
hansol1Author Commented:
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.
TimYatesCommented:
>  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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TimYatesCommented:
> 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()" ) ;

TimYatesCommented:
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 ;
    }
  }
TimYatesCommented:
AND make sure you have put MAYSCRIPT in the applet tag on the HTML page
hansol1Author Commented:
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.
hansol1Author Commented:
Why this error is coming
eval failed with error== com.ms.com.ComFailException: Could not complete the operation due to error 80020101.
thanks
hansol1Author Commented:
PLease help me on my lasr two comment
hansol1Author Commented:
I failed to get return value from java script.Please refer my third last comment.It is returning a String "Undefined"
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.