none
Calling Javascript from C#.NET

    Question

  • Hi,

    I have an HTML page with contains both Javascript and a .NET control on it.

    the html is:
    <html>
        <head>
        </head>
        <body>
            <SCRIPT LANGUAGE="JavaScript" src="javascript/projectJS.js">
            </SCRIPT>
            <OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"     codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"
             WIDTH="100%" HEIGHT="100%" id="project">
              <param name="allowScriptAccess" value="always" />
              <param name='src' value='index.mxml.swf'>
              <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
            </OBJECT>
            <OBJECT id="ProjectControl"    classid="ProjectControl.dll#ProjectControl.ProjectControl" height="0" width="0" />
    </body>
    </html>

    Now I can call methods within the control fine using ProjectControl.scriptPrint(); in the Javascript.

    My question is whether there is a way to do the reverse, call a Javascript method from the .NET control as I haven't found a way of doing this as yet.

    Egor.
    Thursday, March 09, 2006 8:36 AM

Answers

  • Solved! Though it required much head scratching.

    You can pass a reference from the JS to the C# code which it captures and can execute JS script back.

    JS
    function do_Print() {
        control.setPage(this);
        control.scriptPrint();
    }
    function report_back(report){
        alert("Report:"+report);
    }

    C#
    public void setPage(mshtml.HTMLWindow2Class JSFile) {
                window = JSFile;
    }
    public void scriptPrint(){
                window.execScript("report_back('Printing complete!')", "JScript");
    }

    It works perfectly and without ASP.NET!

    thanks for the help anyway.

    Egor.
    Friday, March 10, 2006 3:05 PM

All replies

  • I hope this is what you are looking for, as I have done this myself recently:

    in javascript lets say you have a method called "hi" which expects a parameter.

    :

    <script>

    function hi(var someVar)

    {

       document.write("hi " + someVar);

    }

    </script>

     

    in .NET on a method you wish to call the javascript method from:

    string whatever = "blahblah";

    Page.RegisterStartupScript("myScript", "<script language=JavaScript>hi('" + whatever + "');</script>");

     

    I hope that is what you are looking for and hope it helps!

    • Proposed as answer by AJK11 Wednesday, May 16, 2012 1:24 PM
    Thursday, March 09, 2006 9:19 AM
    Moderator
  • Does this only work in an ASP environment, or can it be utilised with straight html?

    Egor.
    Thursday, March 09, 2006 9:33 AM
  • how do you mean?

     

    this can only be done in ASP.NET I believe - unless there is another way which I am unsure.

    the codebehind is as you may know a .NET file (C#/VB.NET) and the Page.method() stuff/code can only be called within the .NET files (C#/VB.NET/ASP.NET)

     

     

    Thursday, March 09, 2006 1:42 PM
    Moderator

  • this can only be done in ASP.NET I believe - unless there is another way which I am unsure.


    Yeah, I was trying to avoid ASP.NET for various company reasons, so this would be a straight html page with a .NET control hosted in it (as with the code I posted before) and some Javascript controlling some communication interactions (I've ommited another object from the code).

    Setting up some sort of callback to the Javascript from the .NET control is whats stumping me.

    I really don't want to have to go down the ASP.NET route either.

    Any clearer?

    Egor.
    • Proposed as answer by ijaz ahamd Wednesday, September 09, 2009 8:22 AM
    Thursday, March 09, 2006 1:48 PM
  • tut - the company should be using the latest and greatest .NET hehe.

     

    no im sorry, other than that I am unsure! I hope someone else is able to help. :)

    Thursday, March 09, 2006 2:56 PM
    Moderator
  • Solved! Though it required much head scratching.

    You can pass a reference from the JS to the C# code which it captures and can execute JS script back.

    JS
    function do_Print() {
        control.setPage(this);
        control.scriptPrint();
    }
    function report_back(report){
        alert("Report:"+report);
    }

    C#
    public void setPage(mshtml.HTMLWindow2Class JSFile) {
                window = JSFile;
    }
    public void scriptPrint(){
                window.execScript("report_back('Printing complete!')", "JScript");
    }

    It works perfectly and without ASP.NET!

    thanks for the help anyway.

    Egor.
    Friday, March 10, 2006 3:05 PM
  • Egor, is there anyway I can get you to post your C#.NET and JS files. I have a similar situation in .NET 2.0 and for some reason I cannot get javascript to find the method in my C#.NET class. I get the infamous "object doesn't support this property or method" dialog. For example, if your code was mine, control.scriptPrint() would generate the error. I'm not using asp as well.

    thanks

    Gary F.

    Wednesday, March 29, 2006 12:55 AM
  • I am having the same problem as well. Not sure how to expose my method so that javascript can call it. Please post your C# method here.

    Thanks in advance,

    Regards

    Rajen

    Tuesday, September 19, 2006 7:47 AM
  • Check to see if the COM-Visible flag is set in your assembly.  Go to the project properties page and click on the application tab.  There should be an 'Assembly Information..." button.  Click that and at the bottom of the dialog check the 'Make Assembly COM-Visible'.  Hopefully that will fix your problem.

    Michael Ennis

    Friday, September 22, 2006 3:25 PM
  • that did the trick..thanks again..
    Friday, September 22, 2006 7:51 PM
  • Id like to see in detail how you pulled that off if ya don't mind posting some examples.
    Pleeeeeeeeeeeease?
    Tuesday, December 05, 2006 9:20 AM
  • Its quite simple really. Click on the project properties... Then click on the Assembly tag and check the COM visible attribute..

    Cheers

    Rajen

    Wednesday, December 06, 2006 8:37 AM
  • I have to pass a few parameter so my code looks like this;

    <c#>
           private System.Windows.Forms.WebBrowser wb;
           ....
          object[] args = { tVal, nVal};
          wb.Document.InvokeScript("SetCenter", args);

    </c#>

    <javascript>
        function SetCenter(v, n){
          setCenter(v,n);    }
    </javascript>

    Think this only works in .NET v2 or later


     
    Wednesday, February 14, 2007 10:45 PM
  • Hi!

    I tried your solution and it works perfectly on my development machine, but not if a different user from a different machine tries to access the web page.

    I have a web site that hosts a Windows.Forms Control. When a user clicks a button on this control I want to execute a javascript. The C# code is as follows:

            public void setPage(mshtml.HTMLWindow2Class JSFile) {
                window = JSFile;
            }

            public void SayHello()
            {
                String code = "report_back('hello')";
                window.execScript(code, "JScript");
            }

            private void button1_Click(object sender, EventArgs e)
            {
                SayHello();
            }

    And the HTML:
    <html>
    <head>
    <title></title>
    </head>
    <body onload="do_Print()">
    <OBJECT id="keyLogger" classid=
    "http:KeyLoggerControl.dll#Findwise.Controls.KeyLoggerControl"
    width=800 height=300 style="font-size:12;">
    </OBJECT>

    <script language="javascript">
        function do_Print() {
            var ctrl = document.getElementById('keyLogger');
            ctrl.setPage(this);
        }
        function report_back(report){
            alert("Report:"+report);
        }
    </script>
    <br>
    </body>
    </html>

    As I said, this works perfectly on my development machine. However if another user visits this page that is hosted on my machine, the following security exception is raised:
    ************** Exception Text **************
    System.Security.SecurityException: That assembly does not allow partially trusted callers.
    at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
    at Findwise.Controls.KeyLoggerControl.SayHello()
    at Findwise.Controls.KeyLoggerControl.button1_Click(Object sender, EventArgs e)
    at System.Windows.Forms.Control.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnClick(EventArgs e)
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ButtonBase.WndProc(Message& m)
    at System.Windows.Forms.Button.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    The action that failed was:
    LinkDemand
    The Zone of the assembly that failed was:
    Trusted
    **********************************************

    And yes, I have added the [assembly: AllowPartiallyTrustedCallers] attirbute to my AssemblyInfo.cs file and signed the assembly.

    Anyone knows how to solve this?
    Tuesday, June 12, 2007 8:28 AM
  • Glenn,

    thanks for your example. This could save me from a lot of crappy AJAX-control timing problems with using some 3rd-party aspx controls.

    Friday, June 15, 2007 5:33 PM
  • Hi,

    Is there a way to get this C# to JavaScript call working when the C# is multi-threaded?  I have written a .Net control which, when I introduce a new thread into the process and attempt to call the JavaScript from there, gives me the following exception:

    ExceptionTongue Tiedystem.InvalidCastException: Unable to cast COM object of type 'mshtml.HTMLWindow2Class' to interface type 'mshtml.DispHTMLWindow2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3050F55D-98B5-11CF-BB82-00AA00BDCE0B}' failed due to the following error: Unspecified error (Exception from HRESULT: 0x80004005 (E_FAIL)).

    Thanks,
    Chris

    Monday, July 16, 2007 1:28 PM
  • Hi all,
    Sorry for dragging an old thread up but I'm still very new to .Net and I can't seem to figure out this solution.
    I added a reference to the mshtml.tbl file in my project then started adding in the C# code but then I noticed that the "window" value doesn't seem to be declared anywhere in this code Tongue Tied

    What exactly is this window value?

    Something else I noticed was that there doesn't appear to be a source attribute for the HTMLWindow2Class JSFile so I'm not sure exactly how I am supposed to pass in the JavaScript file Tongue Tied

    Can anyone please enlighten me?

    Sorry again for the trouble, hope you will respond Smile
    Thanks.




    Saturday, August 11, 2007 11:10 PM
  • hi all

    i m trying to pass an string array from my C# code to the javascript..but that is not passing its value rather is passes the control's identity..

    how can i achieve this ..

    the code snippet is like this..

    lnkbuttoon.Attributes.Add("onclick", "myFunction(' "+ stringArray +" ') ");

    but stringArray is recieving with value System.string[] or System.Collections.Arraylist (if i pass arraylist)

    any help...

    thanks

    Friday, August 31, 2007 3:20 PM
  • I tried the same thing. Two things happen.

     

    1. I dont get object .

    i.e object = [undefined] / [] / space .. nothing

    2. If I get object then I am not able to acess methods

    i.e. access denied

     

    if not  object is nothing then

    acess_denied  = True

     

    Monday, September 17, 2007 3:37 AM
  • It works with all environment once it works. I know it works for flex client on mac OS haveing C++ dll.

    Monday, September 17, 2007 3:39 AM
  • Hi

    I'm also trying to invoke javascript functions included in .js file and i'm getting error when I try to invoke javascript.

     

    Retrieving the COM class factory for component with CLSID {D48A6EC6-6A4A-11CF-94A7-444553540000} failed due to the following error: 80040154.

     

    Can you please send complete code snippet PLEASE?

    Tuesday, September 18, 2007 10:30 AM
  •  

    Would you mind posting what else needs to be done for a newbie?  I'm looking for tiny sample code that simply allows calling Javascript from C# -- like hello world.  I seem to be missing something because nothing will compile --

    For instance, the keyword "browser" is unknown... are there assemblies & using statements I should be including?

     

    I've included microsoft.mshtml and I'm "using" mshtml but I'm guessing there's more -- but after searching for examples for hours I'm exhausted! :-)

     

    Thanks!

     

    Friday, September 21, 2007 9:14 PM
  •  

    I am using Asp.net 1.1 C#2003

     

    the object window is not available there, how can i get it

     

    please helkp me i want to call a function that exists in JavaScript from C# this is the simple question

    Tuesday, October 23, 2007 8:13 AM
  • hi...

     

      Could u explain with some more sample example.... I cant get u... Is it possible to call a javascript for C# WinForm....

     

    reg

    Inba

    Wednesday, November 14, 2007 12:40 PM
  • Tuesday, July 29, 2008 6:45 PM
  • this can only be done in ASP.NET I believe - unless there is another way which I am unsure.

    the codebehind is as you may know a .NET file (C#/VB.NET) and the Page.method() stuff/code can only be called within the .NET files


    FLVwin is a Flash Fans!
    Friday, September 25, 2009 8:07 AM
  • hi all

    i m trying to pass an string array from my C# code to the javascript..but that is not passing its value rather is passes the control's identity..

    how can i achieve this ..

    the code snippet is like this..

    lnkbuttoon.Attributes.Add("onclick", "myFunction(' "+ stringArray +" ') ");

    but stringArray is recieving with value System.string[] or System.Collections.Arraylist (if i pass arraylist)

    any help...

    thanks


    Technocrat here had the right idea, and I got something similar to work using that idea using ASP .NET to call a JavaScript function:

    First, put the JavaScript function in your HTML Scripts (or external script that is linked to here), like you normally would.  Add a <SPAN id="mySpan" runat="server"> in your HTML page body code.  I was changing the SPAN's innerHTML to a picture from an onclick event of a button, so I used: 

    function activateClock() { 
         document.getElementById('mySpan').innerHTML = "<img src='https://<% =ConfigurationManager.AppSettings["FQDN"] %>/SearchMonitoringSite/images/animated-clock.gif' />"; 
    }

    I got kinda fancy in there - using my web.config for the FQDN - basically just make the src = 'http://www.yourwebsite.com/images/yourimage.jpg'

    Next, add an attribute.add event in the Page_Load section of your code-behind file (Default.aspx.cs):

    protected void Page_Load(object sender, EventArgs e)

    {

    btnYourButton.Attributes.Add( "onclick", "activateClock()");

    }

    Then, when your button is clicked, it will activate the JavaScript function (displaying your image where the span was), as well as performing whatever ASP .NET code you include in a btnYourButton_Onclick(object sender, EventArgs e) function.  Pretty easy, I think.

    -Tom

    • Edited by navyjax2 Thursday, December 17, 2009 5:38 PM span correction, formatting
    • Proposed as answer by navyjax2 Thursday, December 17, 2009 6:00 PM
    Thursday, December 17, 2009 5:32 PM
  • Thanks Ahmedilyas,

    I tried your Page.RegisterStartupScript("myScript", "<script language=JavaScript>hi('" + whatever + "');</script>"); method.

    That worked very well.

    Thanks for sharing it.

    Teva

    Wednesday, June 23, 2010 10:22 PM
  • hi,

     

    I wrote a program for calling the batch file using c#, 

    using system;

    using system.diagnostics;

    string path = "c:\\ftpscript.cmd";

     

    // ftpscript.cmd contans ftp -s: ftp.txt

    //ftp.txt contains command to open the ftp connection.

    //open 123.12.14.0

    //myusername

    //mypassowrd

    //put c:\abc.txt

    //bye.

    var procStartInfo = new ProcessStartInfo(path, "")

                    {

     

                        CreateNoWindow = false,

                        UseShellExecute = false,

                        RedirectStandardOutput = true,

                        RedirectStandardError = true,

                        RedirectStandardInput = true

                    };

     

                    var proc = new Process { StartInfo = procStartInfo };

                    proc.Start();

                

        proc.StandardInput.Flush();

     

                    // Get the output into a string

                    string result = proc.StandardOutput.ReadToEnd();

                    string error = proc.StandardError.ReadToEnd();

     

     

    But I am using the windows forms application, and i want to pass all the parameters from tesxtboxes of myusername,mypassword,and abc.txt file.

     

    please some one help me ASAP,

     

    Thank you.. 

    Monday, July 19, 2010 11:30 PM
  • Thank you, ahmedilyas, exactly what I needed.

    Page.RegisterStartupScript has been deprecated and replaced with:

    ClientScript.RegisterClientScriptBlock(Type, string, string);

    So.., using your example:

    Type csType = this.getType();

    ClientScript.RegisterClientScriptBlock(csType, "myScript", "<script type='text/javascript'>hi('" + 

                    whatever + "');</script>");

     

    Thanks again.

    Tuesday, August 10, 2010 4:27 PM
  • Hi ,

    Error 4 The name 'window' does not exist in the current context

     

    I am having this error .

    Can anyone help me urgently please

     

    Thanks

    • Proposed as answer by Gowes Tuesday, February 07, 2012 5:36 AM
    Monday, August 30, 2010 10:49 AM
  • Can you post the whole code please

     

    thanks

    Monday, August 30, 2010 10:50 AM
  • You can ClientScriptManager clss method RegisterClientScriptBlock or RegisterStartupScript method to invoke JavaScript Method.

    Refer to below links for more details about the same.

    Friday, September 10, 2010 10:09 AM
  • HI CHrish68,

        Was the problem solved?I had the same problem, if you had solved the problem.please tell me,thanks

    Tuesday, November 30, 2010 6:04 AM
  • Hello pengyuanyuan0930

     

    Please tell me to run javascript in windows form application in C#

    I you have some knowledge regarding this please share with me I have done lot of googling on this.

    With Webrequest and webresponse I am getting response back

    But I want to find more by runing the javascript.

    Regards

    Asif


    Asif Chouhan
    Wednesday, December 01, 2010 11:30 AM
  • Hi all,
    Sorry for dragging an old thread up but I'm still very new to .Net and I can't seem to figure out this solution.
    I added a reference to the mshtml.tbl file in my project then started adding in the C# code but then I noticed that the "window" value doesn't seem to be declared anywhere in this code Tongue Tied

    What exactly is this window value?

    Something else I noticed was that there doesn't appear to be a source attribute for the HTMLWindow2Class JSFile so I'm not sure exactly how I am supposed to pass in the JavaScript file Tongue Tied

    Can anyone please enlighten me?

    Sorry again for the trouble, hope you will respond Smile
    Thanks.

    +1, I have even purchased a programming book for dummies and I have yet to figure this out, I too, am having problems with the window value recognizing my mshtml.tbl file. Can someone please me thorough in their answer?
    Thanks!


    term life insurance
    Saturday, April 30, 2011 2:39 PM
  • How do I mshtml.HTMLWindow2Class in a WindowsForm (for Expample with a webBrowser tool) ?
    Monday, March 12, 2012 10:34 AM
  • You can download sample program from this linkhttps://skydrive.live.com/#cid=2F22272220E37707&id=2F22272220E37707%21103 project name is CodeBehingCallJavaScriptiFunction you can download

    and feel free to ask anything you can contact me with email skygocomputer@yahoo.co.in

    Sunday, July 29, 2012 6:46 AM