使用C#将javascript注入BHO——如何正确转义字符串
我有以下C#中的代码,我可以将其附加到IE,它运行良好,直到我点击JSON,我收到一个javascript错误,抱怨语法。我应该如何在C#中转义javscript代码使用C#将javascript注入BHO——如何正确转义字符串,c#,javascript,bho,C#,Javascript,Bho,我有以下C#中的代码,我可以将其附加到IE,它运行良好,直到我点击JSON,我收到一个javascript错误,抱怨语法。我应该如何在C#中转义javscript代码 string jsonStr=@“[ {\'name\':\'Obj1\',\'description\':\'Test description…\',\'url\':\'http://www.test.com\' }, {'name\':'Obj2\','description\':'Testing…','url\':'http
string jsonStr=@“[
{\'name\':\'Obj1\',\'description\':\'Test description…\',\'url\':\'http://www.test.com\' },
{'name\':'Obj2\','description\':'Testing…','url\':'http://www.test.com\' },
{'name\':'Obj3\','description\':'Welp…','url\':'http://www.test.com\' }
]";
IHTMLScript元素scriptObject=(IHTMLScript元素)document.createElement(“脚本”);
scriptObject.type=@“text/javascript”;
scriptObject.text=@“函数测试(){
var Edit='document.getElementById(\'tTest\')。innerHTML='Foo';
var json=“+jsonStr+@”;
$.each(json,函数(索引,x){
编辑+=''+x.url+'+x.description+' ;
});
编辑+='\';
评估(“编辑”);
}";
((HTMLHeadElement)head.appendChild((IHTMLDOMNode)scriptObject);
IHTMLDocument2 doc=(IHTMLDocument2)此文件;
IHTMLWindow2 parentWindow=doc.parentWindow;
if(parentWindow!=null)
execScript(“test();”,“javascript”);
c#代码很好,我只是在用所有引号、单引号等注入javascript代码以消除javascript错误方面遇到了麻烦。非常感谢您的帮助 当使用前缀为@的逐字字符串文字时,这意味着将包含的字符串视为文字。所以基本上没有反斜杠“\”逃逸。要转义双引号(“”),只需将其加倍(“”)
哪一行有错误?它从我在C#中构建的JSON字符串开始,我相信它需要一个双引号,但是当我切换出“for”时,我得到了一个.NET编译器错误(因为它关闭了字符串)
string jsonStr = @"[
{ \'name\': \'Obj1\', \'description\': \'Test description...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj2\', \'description\': \'Testing...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj3\', \'description\': \'Welp...\', \'url\':\'http://www.test.com\' }
]";
IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
scriptObject.type = @"text/javascript";
scriptObject.text = @"function test() {
var Edit = 'document.getElementById(\'tTest\').innerHTML = \'<h2 class=\'label3\'><span>Foo</span></h2><ol class=\'container-list\'>';
var json = '" + jsonStr + @"';
$.each(json, function (index, x) {
Edit += '<li class=\'test1\'><h3><a href=\'#\'><b>' + x.name + '</b> 1</a></h3><div class=\'url\'><cite>' + x.url + '</cite></div><div class=\'creative\'>' + x.description + '</div></li>';
});
Edit += '</ol>\';
eval('Edit');
}";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
IHTMLDocument2 doc = (IHTMLDocument2)this._webBrowser2.Document;
IHTMLWindow2 parentWindow = doc.parentWindow;
if (parentWindow != null)
parentWindow.execScript("test();", "javascript");
string jsonStr = @"[
{""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }
]";