There are frequently times when you want to include user content in your applications, sometimes even within JavaScript. Proper usage of Solstice, along with some best practices, can allow this while keeping you and your users safe.
Client Actions
If you want to include user content in a client action - for example, using a confirmation dialog when deleting something, you can use StringLibrary's strtojavascript method to make things safe.
Perl
use Solstice::StringLibrary qw(strtojavascript);
sub generateParams {
my $self = shift;
my $object = shift;
my $title = $object->getTitle();
my $confirm_string = "Are you sure you want to delete '$title'?";
$confirm_string = strtojavascript($confirm_string);
my $delete_button = $self->getButtonService()->makeButton('delete_obj');
$delete_button->setClientAction("confirm('$confirm_string')");
$self->setParam('delete_button', $delete_button->getTextLink());
}Other JavaScript
If you have a method you want to call using user content, strtojavascript is again the way to go, but you need to be a bit more cautious in your template.
Perl
use Solstice::StringLibrary qw(strtojavascript);
sub generateParams {
my $self = shift;
my $object = shift;
$self->setParam('obj_title', strtojavascript($object->getTitle()));
}<script>
<!--
call_method('<!-- sol_var obj_title -->');
-->
</script>
Without the html comment notation, a </script> in user content can lead to problems.
Attaching events to DOM elements
Another source of trouble is adding events to DOM elements. If you add an onhover, or onmouseover event as part of the tag, user content with a quote character can cause you problems. Here's the correct way to handle that situation.
<a id="foo" href="javascript:void(0);">bar</a>
<script>
<!--
var bad_string = 'test\'</script>\"\\';
Solstice.Event.add(document.getElementById('foo'), 'click', function() {alert(bad_string) });
-->
</script>
Where bad_string could be a sol_var that had strtojavascript applied to it.