Hi,

I want to be able to call a Javascript file from a C# Windows Application. This is just a stand alone C# application.
What I want to be able to do is to execute this JavaScript file, think of it as a function, and be able to pass parameters into it and to receive a return result from it.

Any help is appreciate, thanks!

As a scripting language, JavaScript acts on the underlying Object Model of its host. In a web environment, this means the browser/web page. In Acrobat, this means the various objects exposed by Acrobat (AVDoc, PDDoc, etc.). So not only can you not arbitrarily execute a "JavaScript" from C#, it's a meaningless concept. What would such a script "do" or act upon?

It is possible, though, to write a C# program that interacts with another program that supports JavaScript. For example, you can embed a Web Browser control on your C# form, and load HTML documents in it that in turn use JavaScript functions... or use IAC to communicate with Acrobat and load PDFs that use JavaScript internally.

You'll have to paint a clearer picture for us.

Let me try to explain what I try to do:

I've created a crawler in C#. The crawler is reading an URL in a text file and load this URL into a WebBrowser embedded on the C# form. Then it tries to recover information in the page like the keywords or the value of varaibles.
My problem is that I need to execute javascript code to get the value of some variables...

I hope this is clear enough.

You can't. The page you are crawling has to "execute" the JavaScript embedded on the page. I'm not sure why you'd want to capture JavaScript variables anyway, since they are only used to render content on the page. In other words, a JavaScript variable might be used to control the position of an element or the value of a textbox, something your crawler should be able to capture directly. Otherwise, you'd be trying to capture an "interim" state of the page.

Think of it this way, c# codebehind runs on the server not on the client. I can do things with the html document, sniff the request for variables and such but you cant execute client side scripts via serverside code.

If you try this you will see what I am talking about.

On a buttons click event add "Messagebox("BUTTON WAS CLICKED");"

When you run it in VS, you will def see the message box, but that is only because you are on the server. If you deploy the app to a server and access it from a client on a diff machine, the client seems to hang. But if you go to the server, you will see your message box! Once you click ok the client responds.

You can't. The page you are crawling has to "execute" the JavaScript embedded on the page. I'm not sure why you'd want to capture JavaScript variables anyway, since they are only used to render content on the page. In other words, a JavaScript variable might be used to control the position of an element or the value of a textbox, something your crawler should be able to capture directly. Otherwise, you'd be trying to capture an "interim" state of the page.

actually YOU CAN load javasrcipt from string to an IExplorer instance provided that it was launched from c# app.

dont ever say u cant in PROGRAMMING!

look up
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Runtime.InteropServices;
using mshtml; // Microsoft.mshtml primary Interop assembly
using SHDocVw;

namespace CADIT
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public SHDocVw.ShellWindows SWs;
        public SHDocVw.InternetExplorer IE;
        private void Form1_Load(object sender, EventArgs e)
        {
            Clipboard.Clear();
            SHDocVw.ShellWindows SWs = new ShellWindows();   
            IE = new InternetExplorer();
            IE.Visible = true;
            object o = new object();
            IE.Navigate("http://www.google.com", ref o, ref o, ref o, ref o);
                         
        }

        private void btnCadit_Click(object sender, EventArgs e)
        {
           //SHDocVw.InternetExplorer IE = new InternetExplorer();
            String code;

            
            //
            if (IE.ReadyState >= tagREADYSTATE.READYSTATE_LOADED){
                // read boxify.js
                // (file system really reads this file only once, it uses the cache always until updated)

                FileStream fin = new FileStream("boxify.js", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader tr = new StreamReader(fin);
                code = tr.ReadToEnd();
                tr.Close();
                fin.Close();

                if (code.Length == 0) Console.WriteLine("Cannot find boxify.js file");
            }
            else
            {
              // stop boxify.js
                code = "document.onmouseover = null; document.onmouseout = null;";
            }

            try
            {
                IHTMLDocument2 doc = (IHTMLDocument2)IE.Document;
            
            
           if (doc != null)
                {
                    IHTMLWindow2 parentWindow = doc.parentWindow;
                    if (parentWindow != null)
                        parentWindow.execScript(code, "javascript");
                }
                Get_Clip();  
            }
            catch { }
            }

        private void Get_Clip()
        {
            // Declares an IDataObject to hold the data returned from the clipboard.
            // Retrieves the data from the clipboard.
            IDataObject iData = Clipboard.GetDataObject();

            // Determines whether the data is in a format you can use.
            if (iData.GetDataPresent(DataFormats.Rtf))
            {
                // Yes it is, so display it in a text box.
                //this.richTextBox1.Rtf = (string)iData.GetData(DataFormats.Rtf);
            }
            else
            {
                // No it is not.
               // textBox2.Text = "Could not retrieve data off the clipboard.";
            }
        }

        private void btnOff_Click(object sender, EventArgs e)
        {
             // stop boxify.js                   
             String code = "document.onmouseover = null; document.onmouseout = null;";
              try
                {
                    IHTMLDocument2 doc = (IHTMLDocument2)IE.Document;
                       
           if (doc != null)
                {
                    IHTMLWindow2 parentWindow = doc.parentWindow;
                    if (parentWindow != null)
                        parentWindow.execScript(code, "javascript");
                }
                 }
                catch { }

                 IDataObject clipData = Clipboard.GetDataObject();

                 //retrieve an array of strings for all the formats available on the clipboard.
                 string[] formats = clipData.GetFormats();

                 //iterate through the list of formats on the clipboard
                 foreach (string format in formats)
                 {
                     //add each objeoct to an arraylist so we can inspect the object types
                     object dataObject = clipData.GetData(format);
                     MessageBox.Show (dataObject.ToString());

                 }


                
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();
            this.Close();      
        }

        }
    }

Edited 6 Years Ago by Nick Evan: Add code-tags

i have some problem when i did a project about SPIDER (SPIDER is written by C#, winform)
for example:

i get HTML from URL http://www.WebsiteName.com and from HTML i got, have some javascript functions, and i want to get result from these javascript functions

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">
    function getText()
    {
        var object1 = document.getElementById("Text1");        
        return object1.value; 
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<input id="Text1" type="text" />
        <input id="Button2" type="button" value="button" onclick="return getText()" />
        <input id="Text2" type="text" /></div>
    </form>
</body>
</html>

in this example : i am to get result from function getText()
can you help me

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Wow, such cynical and rude comments!

If you're using a webbrowser control in C# then you can call javascript functions and get the return value... just use WebBrowser.Document.InvokeScript("example_function", args); where args is an array of the type object.

Comments
Help us to help you.
Don't bump old threads
This article has been dead for over six months. Start a new discussion instead.