views:

1387

answers:

6

I have the following JavaScript code as a string literal:

var $Page = new function()
{
    var _url= 'http://www.some.url.com';

    this.Download = function()
    {
        window.location = _url;
    }
}

Is there a way I could get the value of the _url variable from my C# code? An open source library perhaps? I did this using a Regular Expression, but I was hoping for a more elegant way.

+2  A: 

I'd say go for a Regular Expression, because it works. Why is it not elegant?

PoweRoy
It is, I'm just looking for another way to do it.
hmemcpy
A: 

You could execute the javascript function using the DLR and/or MyJScript.

sipwiz
A: 

If it's a string literal, why not just copy and paste the URL into a new string literal?

Or did I take your question too literally (ho ho), and the string is being read from somewhere else?

Blorgbeard
Well, it's a literal in the unit test, but I'm scraping it from an HTML page at runtime...
hmemcpy
Ah, now I see :)
Blorgbeard
+2  A: 

You could use a javascript parser, but parsing javascript for just that one value is probably way overkill.

Brian
A: 

There is an open-source JavaScript interpreter in C# at http://jint.codeplex.com, if you need more than just getting the value.

Sébastien Ros
+1  A: 

You should take a look at the open-source Javascript .NET (http://javascriptdotnet.codeplex.com/) on Codeplex.

This sample of code should help you:

Javascript context = new JavascriptContext();
context.Run("var _url= 'http://www.some.url.com';") // You put your javascript in the function run
String url = (String)context.GetParameter("_url"); // You get your url from javascript

That's it.

Deacon Frost