views:

41

answers:

2

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) 
        {
            alert('Test')
            return "PROXY myproxy.local:8080";
        }
}

And getting an error on -

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

{C:\Users\Me\AppData\Local\Temp\zfwspah4.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?

+1  A: 

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.

T.J. Crowder
A: 

To elaborate a bit on what's been said.

The window object is part of the Domain Object Model of a web browser, strictly speaking it's not a javascript object but merely a javascript interface to a browser object,a proxy if you like. As such, and the DOM reference kind of gives this away, it's specific to the execution domain, i.e. it's only available to a javascript interpreter within a web browser than provides a DOM to it. As alert is a method of the window object you are rather stuck without the DOM.

As TJ mentions, if you want a pop-up alert window available to your compiled javascript app then you are going to have to implement it for yourself and I'll be honest that I don't know where to start there. It's very much outside the scope of this question.

Lazarus