Javascript Compiler in .Net giving errors

I have the following code:

 Dim compiler As ICodeCompiler = New Microsoft.JScript.JScriptCodeProvider().CreateCompiler
      Dim params As New CompilerParameters
      params.GenerateInMemory = True

      Dim res As CompilerResults = compiler.CompileAssemblyFromSource(params, TextBox1.Text.Trim)
      Dim ass As Assembly = res.CompiledAssembly
      Dim instance As Object = Activator.CreateInstance(ass.GetType("Foo"))

      Dim thisMethod As MethodInfo = instance.GetType().GetMethod("FindProxyForURL")
      Dim str(1) As String
      str(0) = ""
      str(1) = ""

MessageBox.Show(thisMethod.Invoke(instance, str))

Trying to compiler the folowing JavaScript code:

class Foo {

    function FindProxyForURL(url, host) 
            return "PROXY myproxy.local:8080";

And getting an error on –

 compiler.CompileAssemblyFromSource(params, TextBox1.Text.Trim)

{C:UsersMeAppDataLocalTempzfwspah4.0.js(4,65) : error JS1135: Variable ‘alert’ has not been declared}

If i remove the “alert” line it works fine. I gather this is because alert is a “window” object, so .Net doesn’t recognise it. I have tried replacing it with window.alert(”) but still get the same error.

How can i fix this?


alert is a function supplied by some host environments (for instance, browsers have it, but servers probably don’t). Changing from alert to window.alert didn’t make any difference because (on a browser) it comes to the same thing. (window is a property of the global object that refers back to the global object. alert is a property of the global object that refers to a host-provided function. So window.alert is the same as alert is the same as window.window.window.alert. But I digress…)

You’ll have to use (and probably import, or receive as a function parameter, etc.) whatever mechanism is provided by the host environment in which you’re going to run your compiled JavaScript.