nthpixel
nthpixel

Reputation: 3109

C# - Read JavaScript file and access variable

I have a JavaScript file with variables defined and values assigned to them. Is it possible to read the .js file with C# and easily retrieve the variables and values? I know what the variable names will be, but the values will be a json string. I'm hoping I don't have to resort to regular expressions.

EDIT: I do not have control over the contents of the JavaScript file. A third party drops the file to a location and I need to pick it up, read it, and parse it.

EDIT 2: Ok, forget I mentioned json. That actually has nothing to do with my question...which at this point doesn't seem to have a simple solution. So I went with reading the .js file line by line, searching for the variable name, and getting the value. Code below for reference.

using (StreamReader r = new StreamReader("myFile.js"))
{
  while(r.Peek() >= 0)
    {
      var line = r.ReadLine();
      if(line.IndexOf("myVariableName") > -1)
      {
         var arr = line.split("=");
         var variable = arr[0].Trim();
         var value = arr[1].Trim();
      }
    }
}

Upvotes: 2

Views: 8135

Answers (2)

Kris
Kris

Reputation: 2123

I had a similar issue in a Browser Helper Object I needed to to create to extract data from a web generated report and store it in a local file system.

I did following to access js values:

mshtml.IHTMLDocument document = (mshtml.IHTMLDocument)this.Explorer.IWebBrowser_Document;
object script = document.Script;

if (script != null)
{
    // Make the call:
    var jsvar = script.GetType().InvokeMember("eval", BindingFlags.InvokeMethod, null, script, new object[] { "HIS_VisitNumber" });

    // Cast...
    _strHISVisit = (string)jsvar;

    // Release the script object, and possibly the document object.
    Marshal.ReleaseComObject(script);
}

Here this.Explorer is the explorer object that is available through the Band Object (the BHO).

But of course, this approach is only possible if you would be able to leverage a browser (IE) which has all the facilities to load and execute js.

If you could not do such a thing, I guess what you would need is a full C# js parser or am I not understanding your question correctly?

In the latter case, you could use Javascript .NET

Upvotes: 2

HamidrezaTA
HamidrezaTA

Reputation: 29

If you are a web developer and want to send data from a JavaScript file (client side) to a C# file (server side), you can use jQuery Ajax. You can pass variables to a function in a C# file. Remember that you must add the [WebMethod] attribute to your C# function, and the function must be static.

$.ajax({
      type: "post",
      url: "Default.aspx/YourMethodName",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify({ varOne: one , varTwo:two }),
                success: function (v) {
                    alert("Success");
                },
                error: function (error) {
                    alert("Error");
                },
                complete: function () {
                    alert("Complete");
                }
            });

Upvotes: 1

Related Questions