1# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: 2 3# Copyright 2016-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> 4# 5# This file is part of qutebrowser. 6# 7# qutebrowser is free software: you can redistribute it and/or modify 8# it under the terms of the GNU General Public License as published by 9# the Free Software Foundation, either version 3 of the License, or 10# (at your option) any later version. 11# 12# qutebrowser is distributed in the hope that it will be useful, 13# but WITHOUT ANY WARRANTY; without even the implied warranty of 14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15# GNU General Public License for more details. 16# 17# You should have received a copy of the GNU General Public License 18# along with qutebrowser. If not, see <https://www.gnu.org/licenses/>. 19 20"""Utilities related to javascript interaction.""" 21 22from typing import Sequence, Union 23 24_InnerJsArgType = Union[None, str, bool, int, float] 25_JsArgType = Union[_InnerJsArgType, Sequence[_InnerJsArgType]] 26 27 28def string_escape(text: str) -> str: 29 """Escape values special to javascript in strings. 30 31 With this we should be able to use something like: 32 elem.evaluateJavaScript("this.value='{}'".format(string_escape(...))) 33 And all values should work. 34 """ 35 # This is a list of tuples because order matters, and using OrderedDict 36 # makes no sense because we don't actually need dict-like properties. 37 replacements = ( 38 ('\\', r'\\'), # First escape all literal \ signs as \\. 39 ("'", r"\'"), # Then escape ' and " as \' and \". 40 ('"', r'\"'), # (note it won't hurt when we escape the wrong one). 41 ('\n', r'\n'), # We also need to escape newlines for some reason. 42 ('\r', r'\r'), 43 ('\x00', r'\x00'), 44 ('\ufeff', r'\ufeff'), 45 # https://stackoverflow.com/questions/2965293/ 46 ('\u2028', r'\u2028'), 47 ('\u2029', r'\u2029'), 48 ) 49 for orig, repl in replacements: 50 text = text.replace(orig, repl) 51 return text 52 53 54def to_js(arg: _JsArgType) -> str: 55 """Convert the given argument so it's the equivalent in JS.""" 56 if arg is None: 57 return 'undefined' 58 elif isinstance(arg, str): 59 return '"{}"'.format(string_escape(arg)) 60 elif isinstance(arg, bool): 61 return str(arg).lower() 62 elif isinstance(arg, (int, float)): 63 return str(arg) 64 elif isinstance(arg, list): 65 return '[{}]'.format(', '.join(to_js(e) for e in arg)) 66 else: 67 raise TypeError("Don't know how to handle {!r} of type {}!".format( 68 arg, type(arg).__name__)) 69 70 71def assemble(module: str, function: str, *args: _JsArgType) -> str: 72 """Assemble a javascript file and a function call.""" 73 js_args = ', '.join(to_js(arg) for arg in args) 74 if module == 'window': 75 parts = ['window', function] 76 else: 77 parts = ['window', '_qutebrowser', module, function] 78 code = '"use strict";\n{}({});'.format('.'.join(parts), js_args) 79 return code 80 81 82def wrap_global(name: str, *sources: str) -> str: 83 """Wrap a script using window._qutebrowser.""" 84 from qutebrowser.utils import jinja # circular import 85 template = jinja.js_environment.get_template('global_wrapper.js') 86 return template.render(code='\n'.join(sources), name=name) 87