4

How to get javascript variable value from DOM using CsQuery?

<script type="text/javascript">
    dealerdata = "HelloWorld"
</script>

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.