4

How to get javascript variable value from DOM using CsQuery?

<script type="text/javascript">
    dealerdata = "HelloWorld"
</script>
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98

1 Answers1

2

CsQuery only parses HTML - not javascript. So you could easily get ahold of the contents of the script block like this:

CQ dom = @"<script type='text/javascript'>
               dealerdata = 'HelloWorld'
           </script>";

var script = dom["script"].Text();
// script == "dealerdata = 'HelloWorld'

... but then you're on your own, it's JavaScript. In your example it would be trivial:

string[] parts = script.Split('=');
string value = parts[1].Trim();

.. but this is only because you know exactly what the input looks like. For typical use cases where you're not sure exactly what context your target could be in, that won't help you much.

If you need to parse Javascript in .NET I'd recommend the Jurassic project, an awesome JavaScript compiler. If speed is of utmost importance, look at javascript.net. This wraps Google's V8 engine and will be a lot faster than Jurassic, but will have non-.NET dependencies.

Oliver Bock
  • 4,829
  • 5
  • 38
  • 62
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119