How can I properly escape JavaScript in JavaScript

2019-02-27 09:54发布

问题:

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?

回答1:

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);


回答2:

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.



回答3:

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>';