2

I'm using selenium and Python and I am trying to execute a JS function that takes in a string like so:

browser.execute_script("foo('someString')")

This works when someString does not have any newlines. When there is a newline character the following happens:

\n     => Parse Error
\\n    => Newline is converted to a space
\r\n   => Parse Error
\\r\\n => Both characters are converted to a space

Is there a way to do this?

2 Answers 2

5

You can pass arguments to the javascript; those additional arguments are accessible using arguments:

browser.execute_script("foo(arguments[0])", 'someString')
browser.execute_script("foo(arguments[0])", 'string with \n is also ok!\n')
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the quick reply. I don't get a parse error anymore but the newlines are being removed alltogether. So the string "hello\nworld" becomes "helloworld".
@MinaHany, How do you confirm that newlines are gone? Could you try this: browser.execute_script("console.log(arguments[0])", 'hello\n newline')
@MinaHany, If the foo write the string to html, you may need to convert newlines something like <br>: browser.execute_script("foo(arguments[0])", 'hello\n newline\n'.replace('<br>'))
You were right, the problem was not selenium. There was a function 3 levels down from foo() that removes the newline. Thanks for pointing me in the correct direction! However to solve my problem I need to somehow override the function that removes the newline (I know its name). Is it possible to do that in selenium before executing the foo function?
@MinaHany, Could you post a separate question with the content of the functions? Without seeing it I can't answer.
|
1

The easy solution is to convert \n to unicode \u000a.

similar example:

driver.execute_script("document.getElementById('website_name').value='hello1\u000ahello2'")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.