8

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.

Igal Tabachnik
  • 31,174
  • 15
  • 92
  • 157

4 Answers4

6

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
  • 265
  • 5
  • 7
5

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

This is now moved to GITHUB

Shiroy
  • 1,648
  • 1
  • 15
  • 22
Sébastien Ros - MSFT
  • 5,091
  • 29
  • 31
  • +1 for a solution that is portable on any .NET platform (I'm using Mono) and doesn't require an external executable. – raider33 Nov 07 '14 at 13:21
0

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

sipsorcery
  • 30,273
  • 24
  • 104
  • 155
0

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

Brian
  • 25,523
  • 18
  • 82
  • 173