Calling Javascript from C#.NET
- 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
- 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
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!
- Does this only work in an ASP environment, or can it be utilised with straight html?
Egor. 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)
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
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. :)
- 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. 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.
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
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
- that did the trick..thanks again..
- Id like to see in detail how you pulled that off if ya don't mind posting some examples.
Pleeeeeeeeeeeease? Its quite simple really. Click on the project properties... Then click on the Assembly tag and check the COM visible attribute..
Cheers
Rajen
- 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
- 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? 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.
- 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:
Exception
ystem.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 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
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
Can anyone please enlighten me?
Sorry again for the trouble, hope you will respond
Thanks.- 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 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
It works with all environment once it works. I know it works for flex client on mac OS haveing C++ dll.
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?
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!
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
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
- How To Call Javascript function in asp.net
http://www.velocityreviews.com/forums/t70627-how-to-call-javascript-function-in-aspnet.html - fhfhg dlgdf gdfklgd gdkgd ggdfgdfg gdfgdfg
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!


