Clean up javascript_escape

This commit is contained in:
Florian Bruhin 2014-05-12 14:33:12 +02:00
parent fd43248d89
commit db7077d94f
2 changed files with 8 additions and 10 deletions

View File

@ -269,12 +269,11 @@ class JavascriptEscapeTests(TestCase):
STRINGS = [ STRINGS = [
('foo\\bar', r'foo\\bar'), ('foo\\bar', r'foo\\bar'),
('foo\nbar', r'foo\nbar'), ('foo\nbar', r'foo\nbar'),
('foo\tbar', r'foo\tbar'),
("foo'bar", r"foo\'bar"), ("foo'bar", r"foo\'bar"),
('foo"bar', r'foo\"bar'), ('foo"bar', r'foo\"bar'),
] ]
def test_escape(self): def test_fake_escape(self):
for before, after in self.STRINGS: for before, after in self.STRINGS:
self.assertEqual(webelem.javascript_escape(before), after) self.assertEqual(webelem.javascript_escape(before), after)

View File

@ -126,19 +126,18 @@ def rect_on_view(elem):
def javascript_escape(text): def javascript_escape(text):
"""Escape values special to javascript in strings. """Escape values special to javascript in strings.
This maybe makes them work with QWebElement::evaluateJavaScript. With this we should be able to use something like:
Maybe. elem.evaluateJavaScript("this.value='{}'".format(javascript_escape(...)))
And all values should work.
""" """
# This is a list of tuples because order matters, and using OrderedDict # This is a list of tuples because order matters, and using OrderedDict
# makes no sense because we don't actually need dict-like properties. # makes no sense because we don't actually need dict-like properties.
replacements = [ replacements = [
('\\', r'\\'), ('\\', r'\\'), # First escape all literal \ signs as \\
('\n', r'\n'), ("'", r"\'"), # Then escape ' and " as \' and \"
('\t', r'\t'), ('"', r'\"'), # (note it won't hurt when we escape the wrong one)
("'", r"\'"), ('\n', r'\n'), # We also need to escape newlines for some reason.
('"', r'\"'),
] ]
text = text.rstrip('\n')
for orig, repl in replacements: for orig, repl in replacements:
text = text.replace(orig, repl) text = text.replace(orig, repl)
return text return text