Using C# and Selenium to enter multi lined SQL text into a Code Mirror textbox on a webpage
When setting the value in JavaScript, you likely need to re-escape the carriage return and newline characters:
var sql = @"SELECT foo
FROM bar";
var jsString = sql.Replace("\r", "\\r")
.Replace("\n", "\\n");
js.ExecuteScript("arguments[0].CodeMirror.setValue(\"" + jsString + "\");", codeMirror);
The resulting JavaScript line would be:
arguments[0].CodeMirror.setValue("SELECT foo\n\rFROM bar")
Be aware that any double-quotes inside your SQL string will also need to be escaped so they do not prematurely end the JavaScript string:
var sql = @"SELECT foo AS '"bar"'
FROM baz";
var jsString = sql.Replace("\r", "\\r")
.Replace("\n", "\\n")
.Replace("\"", "\\\"");
js.ExecuteScript("arguments[0].CodeMirror.setValue(\"" + jsString + "\");", codeMirror);
So the resulting JavaScript is:
arguments[0].CodeMirror.setValue("SELECT foo AS '\"bar\"'\n\rFROM baz");
To avoid the error simply provide the SQL string as an argument:
js.ExecuteScript("arguments[0].CodeMirror.setValue(arguments[1]);", codeMirror, sql);
Or use back tick quoting:
js.ExecuteScript("arguments[0].CodeMirror.setValue(`" + sql + "`);", codeMirror);