How do I escape a string inside JavaScript code inside an onClick handler?

前端 未结 13 842
半阙折子戏
半阙折子戏 2020-11-28 03:44

Maybe I\'m just thinking about this too hard, but I\'m having a problem figuring out what escaping to use on a string in some JavaScript code inside a link\'s onClick handle

相关标签:
13条回答
  • 2020-11-28 04:06

    I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.

    function noQuote(text)
    {
        var newtext = "";
        for (var i = 0; i < text.length; i++) {
            if (text[i] == "'") {
                newtext += "\"";
            }
            else {
                newtext += text[i];
            }
        }
        return newtext;
    }
    
    0 讨论(0)
  • 2020-11-28 04:08

    I faced the same problem, and I solved it in a tricky way. First make global variables, v1, v2, and v3. And in the onclick, send an indicator, 1, 2, or 3 and in the function check for 1, 2, 3 to put the v1, v2, and v3 like:

    onclick="myfun(1)"
    onclick="myfun(2)"
    onclick="myfun(3)"
    
    function myfun(var)
    {
        if (var ==1)
            alert(v1);
    
        if (var ==2)
            alert(v2);
    
        if (var ==3)
            alert(v3);
    }
    
    0 讨论(0)
  • 2020-11-28 04:09

    Use the Microsoft Anti-XSS library which includes a JavaScript encode.

    0 讨论(0)
  • 2020-11-28 04:15

    Depending on the server-side language, you could use one of these:

    .NET 4.0

    string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")
    

    Java

    import org.apache.commons.lang.StringEscapeUtils;
    ...
    
    String result = StringEscapeUtils.escapeJavaScript(jsString);
    

    Python

    import json
    result = json.dumps(jsString)
    

    PHP

    $result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', 
                                     "\r" => '\\r', "\n" => '\\n' ));
    

    Ruby on Rails

    <%= escape_javascript(jsString) %>
    
    0 讨论(0)
  • 2020-11-28 04:19

    Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.

    0 讨论(0)
  • 2020-11-28 04:20

    Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.

    0 讨论(0)
提交回复
热议问题