简体   繁体   中英

Run javascript in C#

I found a fairly complex function in a greasemonkey script that I would like to use in my C# app. Basically I am parsing a page and I need to collect all or 4 members of var avar = {}; (i haven't done this yet but they are all strings using var avar.name = "val" )

Then I need to call the gm func which returns a string and takes in 3 strings. How can I call the function in C#? I am using .NET 3.5

I'm assuming that you are after some code-reuse on the server-side or in some other freestanding app that processes HTML data.

You can compile (at least a subset of) JavaScript in .net using the Microsoft.JScript.JScriptCodeProvider class -- though note that the class warns

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Once compiled the assembly generated (as specified by the CompilerParameters supplied to the provider) should be dynamically loadable. It would be advisable to examine the generated assembly with a tool like Reflector to see what it is you've actually generated, in terms of classes and namespaces.

Disclaimer -- I've only ever used this technique with the CSharpCodeProvider acting on C# source, but I would expect there to be a reasonable level of compatibility across .net languages for this sort of thing.

EDIT -- For an example of compiling JavaScript from C# see this blog post on Verifying JavaScript syntax using C# .

First, you probably want to consider exactly why you're trying to do this. Is it that you want to use the algorithm from the JS in C#? If so, go ahead. If you want to use C# in client-side code (ie the browser), go investigate Silverlight instead.

Second, I'm not sure that what you're trying to do is actually possible. Depending on what youre trying to achieve, you may be better off translating the Javascript from the Greasemonkey app into C# 3.5 (assuming that the script's licensing conditions allow this), for use in your app.

The translation shouldn't be hugely difficult - C# has been getting more and more like JS in the last few versions. Just watch out for the "var" keyword; it means something slightly different in C# to what it means in JS (contrast "type inference" in C# with "dynamic typing" in JS).

Of course, maintaining both versions of the code after you've done this will be tricky and painful. I recommend keeping 1 authoritative version of the code if you can.

Good luck!

Can you provide more information about your script and what you want to accomplish? Most Greasemonkey scripts interact with the DOM via the use of Javascript. You can run Javascript in C# but the DOM will not be available to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM