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

Injecting javascript with BHO using C# - how to escape strings properly

本文关键字:正确地 转义 转义字符 字符串 javascript- BHO 注入 使用      更新时间:2023-09-26

我在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错误时遇到了麻烦。非常感谢您的帮助!

当使用以@为前缀的逐字字符串文字时,意味着将封闭的字符串视为文字。所以基本上没有反斜杠"''"转义。要转义双引号("),只需将其加倍(")即可。

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