Below python (v. 3.9.7) function is injecting CSS styles, that are loaded from a standard CSS file, into a selenium driver object. While in macOS (11.5.2, homebrew) the styles are applied correctly, in Linux (Ubuntu 20.04) the styles were not applied and this message is thrown out: javascript error: Invalid or unexpected token
So which part of the string is causing the issue and how do I have to preprocess the string before sending it?
def injectCSS(driver, file):
css = Path(file).read_text()
css = css.replace('\n', '')
execute = rf'''
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '{css}';
document.head.appendChild(style);
'''
try:
driver.execute_script(execute)
time.sleep(1)
print('CSS injection done')
except Exception as e:
print(str(e))
UPDATE: I narrowed down the problematic string: it's not the string in the Python variable, it's located inside the loaded CSS file itself and it's the line containing the src
attribute in a @font-face
rule:
@font-face {
font-family: "myfont";
src: url(http://my.font.com/font.woff2) format('woff2');
}
UPDATE 2: Well, thanks to @cruisepandey I figured out the problematic markup in the CSS: it's the single quotes inside the CSS file, e.g. font-family: 'serif';
. Replacing them with double quotes fixes the problem.
Why single quotationmarks in the variable are allowed, but not in the CSS file itself? Also: why does the issue occur in linux and not in macOS?