5

I've a JavaScript file and it contains some methods. I want to call those methods from my winform application. Is it possible? If so can you give me a simple example?

I've tried like this

Process.Start("javascript:showuser('User1');return false;");

But it is not recogniging the showuser method. Because my js file is in remote location (ex : http://mysite.com/userprofile.js)

Can you help me to do this

Thank you

rahul
  • 184,426
  • 49
  • 232
  • 263
Nagu
  • 4,954
  • 14
  • 52
  • 67
  • maybe this [solution](http://stackoverflow.com/questions/5167522/how-to-handle-javascript-events-via-webbrowser-control-for-winforms) can be useful – garik Oct 29 '11 at 08:39

3 Answers3

10

You could use a WebBrowser control. Here's a sample post.

webBrowser1.DocumentText = 
    @"<html><head>
      <script type='text/javascript'>
      function testFunction() {
          alert('test');
      }
      </script>
      </head><body></body></html>";
webBrowser1.Document.InvokeScript("testFunction");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Hi thank you for your response. But can you tell me where can I add js file in my application? or how can i refference to the js file (which is in remote location) – Nagu Jan 01 '10 at 10:35
  • In my example I used inline script, but you can also reference your js using using the `src` attribute: `` – Darin Dimitrov Jan 01 '10 at 10:54
  • Hi.. I'm sorry it is not working for me. I dont know wats the wrong with me. Even that alert msg also not coming.. – Nagu Jan 01 '10 at 11:10
  • 2
    After setting the DocumentText, you have to handle the DocumentCompleted event, and do the InvokeScript call(s) in the handler. – ShdNx Jan 01 '10 at 12:07
8

You could possibly use a reference to Microsoft.JScript.dll, and something like the Evaluator method from here; but what exactly are you trying to do? If you are wanting to script your winform, I would be tempted to use IronPython. If you want to automate a browser, you might use the WebBrowser control.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

for being able to expose COM objects you must set:

[ComVisible(true)]

outside your class (within your namespace)

something like:

namespace webform
{
    [ComVisible(true)]

    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
    }
}
Cahya Dewanta
  • 81
  • 1
  • 8