'JavaScriptException in execute_script method

def send(self, message):
    try:
        textArea = self.driver.find_element_by_xpath("//textarea[@placeholder='Message...']")
        textArea.clear()
        self.driver.execute_script("arguments[0].value='" + message + "'", textArea) # Error right here
        textArea.send_keys(Keys.SPACE)
        sendButton = self.driver.find_element_by_xpath("//button[contains(text(), 'Send')]").click()

    except NoSuchElementException or StaleElementReferenceException as ex:
        print("Исключение в send()")
        print(ex)

Up to this point, the fifth line worked, but now I just can’t figure out what the problem is. And the variables have correct values.

File "D:\PROJECTS\BLD_Project\main.py", line 187, in send
    self.driver.execute_script("arguments[0].value='" + message + "'", textArea)
  File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 878, in execute_script
    return self.execute(command, {
  File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected identifier


Solution 1:[1]

Assuming message is a string, you can use setAttribute inside execute_script like below:

textArea = self.driver.find_element_by_xpath("//textarea[@placeholder='Message...']")
self.driver.execute_script(f"arguments[0].setAttribute('value', '{message}')", textArea)

to pass message variable into textArea web element.

Update:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1