2

I'm trying to execute a JavaScript function to see if an element exists in a webpage, but instead of receiving true/false, I'm getting a SyntaxError.

JavaScript:

javascript: var foo = function() { if (document.getElementById('bar') != null) return true; else return false; }; foo();

Error:

I/chromium: [INFO:CONSOLE(1)] "Uncaught SyntaxError: missing ) after argument list", source: (1)

I've run it through several JavaScript formatters, but I can't find the source of the error. Any ideas?

8
  • Is this an on* attribute? Commented May 12, 2017 at 23:33
  • Cannot reproduce error. Are there portions of steps to reproduce error missing at Question? Commented May 12, 2017 at 23:34
  • Can you add an minimal reproducible example using a stacksnippet? Commented May 12, 2017 at 23:38
  • Apologies, I tagged this as android-webview, but I forgot to include that the error occurs when loading a webpage into an Android WebView, and evaluating JavaScript once the webpage has loaded. Commented May 12, 2017 at 23:40
  • Does it help to remove the javascript: label? How about to simplify the code since it seems you don't really need a function. This should do exactly the same: document.getElementById("bar") != null Commented May 12, 2017 at 23:42

2 Answers 2

2

i had a similar issue when triggering a javascript function in a WebView from the Android native code:

    wb.loadUrl("javascript:process('" + myParameter + ");");

The problem was solved adding a ' before the first closing parenthesis:

    wb.loadUrl("javascript:process('" + cff + "');");

Hope this help, although i can`t see such an error in your code.

Sign up to request clarification or add additional context in comments.

Comments

1

I had a similar issue, and the issue was having singular quotes ' inside a string I wanted to send through javascript.

WebView.loadUrl("javascript:function('" + stringToSend + "')")

The stringToSend variable had singular quotes ' inside it, which, to javascript, ended the string. Javascript expected a ) after the end of the string, hence the error.

To fix this I added the escape character \ in front of every singular quote ' by looping through the stringToSend backwards and inserting them.

2 Comments

have you found any permanent solution for this. If there is more than this special chars than also it will break.
It's best to not use nested quotes if you can avoid it, there are also a few other characters or escape sequences that need to be escaped properly. Check out the "Escape Characters" section here: w3schools.com/js/js_strings.asp. If you have to use them or can't control what goes in there, I would recommend looking up how to sanitize the string properly.

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.