使用C#向BHO注入javascript - 如何正确地转义字符串

时间:2013-11-22 22:56:35

标签: 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://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");

c#代码没问题,我只是在用注释带有所有引号,单引号等的javascript代码来消除javascript错误。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

当使用前缀为@的逐字字符串文字时,表示封闭的字符串被视为文字。所以基本上没有反斜杠'\'逃避。要逃避双引号(“),只需加倍(”“)。

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"" }
]";