Monday, February 21, 2011

How can I properly escape JavaScript in JavaScript?

This might be something I can't do but...

parent.document.getElementById('<?php echo $_GET['song']; ?>')
  .innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';

The onmouseover="heartOver(''); portion breaks my JavaScript. Is there a way to escape the quotes so I can do this?

From stackoverflow
  • Escape nested quotes with a backslash: \'

    Also, never echo user data without validating or sanitizing it:

    $song = $_GET['song'];
    
    // Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
    if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
        // Display error because $song is invalid
    }
    

    OR

    // Sanitize
    $song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);
    
  • It's all just a matter of escaping the quotes properly.

    parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML =
        '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe">'
        + '<img src="images/heart.png" alt="Love!" onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';
    

    Also you're missing and end quote for the alt attribute.

    htw : Nice catch about the missing end quote.
  • Your issue is with escaping quotes. You can escape either a single or double quote by replacing ' or " with \' or '".

    So your code would be:

    parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML = '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe"><img src="images/heart.png" alt="Love! onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

0 comments:

Post a Comment