Ask a questionAsk a question
 

AnswerCalling Javascript from C#.NET

  • Thursday, March 09, 2006 8:36 AMEgorKDie Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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.

Answers

  • Friday, March 10, 2006 3:05 PMEgorKDie Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    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.

All Replies

  • Thursday, March 09, 2006 9:19 AMahmedilyasMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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!

  • Thursday, March 09, 2006 9:33 AMEgorKDie Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Does this only work in an ASP environment, or can it be utilised with straight html?

    Egor.
  • Thursday, March 09, 2006 1:42 PMahmedilyasMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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:48 PMEgorKDie Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Proposed Answer

    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 byijaz ahamd Wednesday, September 09, 2009 8:22 AM
    •  
  • Thursday, March 09, 2006 2:56 PMahmedilyasMVP, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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. :)

  • Friday, March 10, 2006 3:05 PMEgorKDie Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    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.
  • Wednesday, March 29, 2006 12:55 AMGary F Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Tuesday, September 19, 2006 7:47 AMRajen Suchede Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

  • Friday, September 22, 2006 3:25 PMMennis Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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 7:51 PMRajen Suchede Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    that did the trick..thanks again..
  • Tuesday, December 05, 2006 9:20 AMandrewh007 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Id like to see in detail how you pulled that off if ya don't mind posting some examples.
    Pleeeeeeeeeeeease?
  • Wednesday, December 06, 2006 8:37 AMRajen Suchede Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Its quite simple really. Click on the project properties... Then click on the Assembly tag and check the COM visible attribute..

    Cheers

    Rajen

  • Wednesday, February 14, 2007 10:45 PMGlennGraham Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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


     
  • Tuesday, June 12, 2007 8:28 AMTobias Larsson Hult Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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?
  • Friday, June 15, 2007 5:33 PMDan Randolph Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Monday, July 16, 2007 1:28 PMchrish68 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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

  • Saturday, August 11, 2007 11:10 PMfuturechoes Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.




  • Friday, August 31, 2007 3:20 PMb_the_technocrat Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    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

  • Monday, September 17, 2007 3:37 AMSikunj Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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:39 AMSikunj Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    It works with all environment once it works. I know it works for flex client on mac OS haveing C++ dll.

  • Tuesday, September 18, 2007 10:30 AMSreenidbl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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?

  • Friday, September 21, 2007 9:14 PMScottJs Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    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!

     

  • Tuesday, October 23, 2007 8:13 AMmaqk Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    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

  • Wednesday, November 14, 2007 12:40 PMInbaraj Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

  • Tuesday, July 29, 2008 6:45 PMNinthRoad Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
  • Wednesday, September 09, 2009 8:23 AMijaz ahamd Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    fhfhg  dlgdf gdfklgd gdkgd ggdfgdfg gdfgdfg
    •  
  • Friday, September 25, 2009 8:07 AMFLVwin Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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!