在 C# 中解析 JavaScript 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/720678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse JavaScript code in C#
提问by Igal Tabachnik
I have the following JavaScript code as a string literal:
我有以下 JavaScript 代码作为字符串文字:
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.
有没有办法_url
从我的 C# 代码中获取变量的值?也许是一个开源库?我使用正则表达式做到了这一点,但我希望有一种更优雅的方式。
回答by sipwiz
回答by Brian
You could use a javascript parser, but parsing javascript for just that one value is probably way overkill.
您可以使用 javascript 解析器,但仅针对该值解析 javascript 可能有点矫枉过正。
回答by Sébastien Ros - MSFT
There is an open-source JavaScript interpreter in C# at http://jint.codeplex.com, if you need more than just getting the value.
http://jint.codeplex.com 上有一个 C# 中的开源 JavaScript 解释器,如果您需要的不仅仅是获取值。
回答by Deacon Frost
You should take a look at the open-source Javascript .NET (http://javascriptdotnet.codeplex.com/) on Codeplex.
您应该查看Codeplex 上的开源 Javascript .NET ( http://javascriptdotnet.codeplex.com/)。
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.
就是这样。