Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am searching for some technique to execute javascript for filling a form in an already running Firefox from an WinForms C# application.
Posted
Comments
Kornfeld Eliyahu Peter 28-Apr-14 9:16am    
I'm really curious why one should do such a thing?! (In any case - the answer is no, you can't do that)
Zhivko Kabaivanov 28-Apr-14 9:43am    
I want the C# app to use the running Firefox to execute the JS in the firefox to fill one particular form.
Kornfeld Eliyahu Peter 28-Apr-14 9:45am    
I understood your question I merely was asking why? What the problem you try to solve with this solution?!
Zhivko Kabaivanov 28-Apr-14 9:57am    
I want to shoot information to a specific web form in Firefox Linux environment.
Basically the language isn't that important to be C#.
I am searching for method for communication from one application to the linux firefox.
In the past days I came across SeleniumHQ which is very good tool but the downfall was that it creates new instances of the firefox and doesn't use already running one.
gggustafson 28-Apr-14 9:44am    
You are asking that two processes intercommunicate: one you have control over (your WinForms C# application) and one you have no control over (Firefox). Unless you know of a hook into Firefox that is not otherwise known (at least by me), there is no direct way to do what you want. I can think of an indirect way.

1 solution


The C# application HTMLFormData collects data that will be used to fill the contents of an HTML Form, named FormToBeFilled. For this example, I choose to collect three pieces of information (name, state, and date) and provide them to FormToBeFilled. Javascript in the form will use the values to initialize three elements (also name, state, and date).



The C# application's form contains: TextBox name_TB, ComboBox state_CB, DateTimePicker date_DTP, Button revise_data_BUT, and Button exit_BUT. There are labels that label each of the first three components.



It is assumed that FormToBeFilled exists on a server. In the same directory as FormToBeFilled must also exist the output of HTMLFormData which, for this example, will be called CToHTML.txt. This is the AGREED_FILENAME. HTMLFormData writes to this file; FormToBeFilled reads from this file.



There is nothing really special about HTMLFormData. Its source follows. The complete project, including FormToBeFilled, can be found at FillHTMLFromCSharp.zip (9.5 KB).


C#
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace FillHTMLFromCSharp
    {

    // ******************************************** class HTMLFormData

    public partial class HTMLFormData : Form
        {
        const string AGREED_FILENAME = @"C:\Users\Public\CToHTML.txt";

        // ********************************************* OnFormClosing

        protected override void  OnFormClosing ( 
                                            FormClosingEventArgs e )
            {

            base.OnFormClosing(e);

            // do wrapup things
            }

        // ********************************************** HTMLFormData

        public HTMLFormData ( )
            {

            InitializeComponent ( );
            }

        // ****************************************** revise_data_file

        void revise_data_file ( )
            {
            string  date = date_DTP.Text;
            string  message = String.Empty;
            string  name = name_TB.Text;
            object  provided_state = state_CB.SelectedItem;
            string  state = String.Empty;

            if ( String.IsNullOrEmpty ( name ) )
                {
                message = "A name must be provided";
                }
            if ( provided_state == null )
                {
                if ( !String.IsNullOrEmpty ( message ) )
                    {
                    message += Environment.NewLine;
                    }
                message += "A state must be provided";
                }
            else
                {
                state = provided_state.ToString ( );
                }

            if ( String.IsNullOrEmpty ( message ) )
                {
                using ( StreamWriter sw = new StreamWriter (
                                            AGREED_FILENAME,
                                            false ) )
                    {
                    StringBuilder sb = new StringBuilder ( );

                    sb.AppendFormat ( "{0},{1},{2}",
                                      name,
                                      date,
                                      state );
                    sw.Write ( sb.ToString ( ));
                    }
                }
            else
                {
                MessageBox.Show ( message,
                                  "Input Error" );
                }
            }

        // ************************************************* BUT_Click

        void BUT_Click ( object sender, EventArgs e )
            {
            Button  button = ( Button ) sender;
            string  tag = button.Tag.ToString ( ).
                                     ToLower ( ).
                                     Trim ( );

            switch ( tag )
                {
                case "exit":
                    Application.Exit ( );
                    break;

                case "revise_data":
                    revise_data_file ( );
                    break;

                default:
                    throw new ApplicationException ( 
                        "Unrecognized button pressed" );
                }
            }

        } // class HTMLFormData

    } // namespace FillHTMLFromCSharp


Two items of interest:



  • The CToHTML.txt file is placed in the C:\Users\Public\ directory. That allows the program to be run by anyone from anywhere without a security issue. After HTMLFormData completes its execution, the CToHTML.txt file must be copied to the directory in which FormToBeFilled is found. When deployed, the constant AGREED_FILENAME should be modified to point to that same directory, thereby making the copy unnecessary.
  • When writing to the CToHTML.txt file, do not use a StreamWriter WriteLine that places a <cr><lf> at the end of the line. This will cause problems in the Javascript that is to parse the data. Rather use a StreamWriter Write.


For expediency, I included the Javascript within FormToBeFilled. The Javascript executes on window load. FormToBeFilled appears as:


HTML
<!DOCTYPE HTML PUBLIC 
          "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
  <body>
    <form action="">
      <table cellpadding="10" cellspacing="0">
        <tr>
          <td align="right">
            Name
          </td>
          <td align="left">
            <input id="name" 
                   type="text" 
                   style="width: 200px;" 
                   maxlength="100" 
                   title="Enter your name"
                   value="foo" />
          </td>
        </tr>
        <tr>
          <td align="right">
            State
          </td>
          <td align="left">
            <select id="states">
              <option value="AL">AL</option>
              <option value="AK">AK</option>
              <option value="AZ">AZ</option>
              <option value="AR">AR</option>
              <option value="CA">CA</option>
              <option value="CO">CO</option>
              <option value="CT">CT</option>
              <option value="DC">DC</option>
              <option value="DE">DE</option>
              <option value="FL">FL</option>
              <option value="GA">GA</option>
              <option value="HI">HI</option>
              <option value="ID">ID</option>
              <option value="IL">IL</option>
              <option value="IN">IN</option>
              <option value="IA">IA</option>
              <option value="KS">KS</option>
              <option value="KY">KY</option>
              <option value="LA">LA</option>
              <option value="ME">ME</option>
              <option value="MD">MD</option>
              <option value="MA">MA</option>
              <option value="MI">MI</option>
              <option value="MN">MN</option>
              <option value="MS">MS</option>
              <option value="MO">MO</option>
              <option value="MT">MT</option>
              <option value="NE">NE</option>
              <option value="NV">NV</option>
              <option value="NH">NH</option>
              <option value="NJ">NJ</option>
              <option value="NM">NM</option>
              <option value="NY">NY</option>
              <option value="NC">NC</option>
              <option value="ND">ND</option>
              <option value="OH">OH</option>
              <option value="OK">OK</option>
              <option value="OR">OR</option>
              <option value="PA">PA</option>
              <option value="RI">RI</option>
              <option value="SC">SC</option>
              <option value="SD">SD</option>
              <option value="TN">TN</option>
              <option value="TX">TX</option>
              <option value="UT">UT</option>
              <option value="VT">VT</option>
              <option value="VA">VA</option>
              <option value="WA">WA</option>
              <option value="WV">WV</option>
              <option value="WI">WI</option>
              <option value="WY">WY</option>
            </select>
          </td>
        </tr>
        <tr>
          <td align="right">
            Date
          </td>
          <td align="left">
            <input id="date" 
                   type="text" 
                   style="width: 200px;" 
                   maxlength="100" 
                   title="Enter the date"
                   value="bar" />
          </td>
        </tr>
      </table>
    </form>

    <script type="text/javascript">
        window.onload = init;

        function init ( )
          {
          if ( window.XMLHttpRequest )// IE7+, Firefox, Chrome, Opera, Safari
            {
            xmlhttp=new XMLHttpRequest ( );
            }
          else                        // IE6, IE5
            {
            xmlhttp=new ActiveXObject ( "Microsoft.XMLHTTP" );
            }
          xmlhttp.open ( "GET", "CToHTML.txt", false );
          xmlhttp.send ( null );

          response = xmlhttp.responseText;
                                              // name,date,state
          var items = response.split ( "," );

          document.getElementById ( "name" ).value = items [ 0 ];
          document.getElementById ( "date" ).value = items [ 1 ];

          var state = items [ 2 ];
          var states = document.getElementById ( "states" );
          var options = states.options;

          for ( var i = 0; ( i < options.length ); i++ ) 
            {
            if ( options.item ( i ).innerHTML == state ) 
              {
              states.selectedIndex = i;
              break;
              }
            }
          }
    </script>

  </body>
</html>


Hope that helps.

 
Share this answer
 
v3
Comments
Volynsky Alex 29-Apr-14 12:49pm    
Nice!
gggustafson 29-Apr-14 14:00pm    
Thank you. Please vote the solution up.

Gus
Volynsky Alex 29-Apr-14 16:33pm    
OK
Zhivko Kabaivanov 16-Feb-15 9:09am    
How to make the input fields to show unicode characters from the txt file?
gggustafson 16-Feb-15 9:36am    
I'm sorry, I do not understand your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900