4

I'm hitting a very peculiar difference between the Android browser and a WebView. Namely, I have the following markup:

<script type="text/javascript">
    <!--

    // some js code...

    // -->
</script>

Now, in the browser, this works perfectly fine. However, when loading the markup in the WebView using loadData(markup, "text/html", "utf-8"), the JavaScript code is not executed at all.

Now, if I remove the HTML comment tags (<!-- and -->), it works fine in the WebView as well. However, this is not something that I want to do, because the markup is coming from a web service that I'd rather not change.

Is there something I can do with the WebView to accept this markup?

Felix
  • 88,392
  • 43
  • 149
  • 167
  • FWIW, http://stackoverflow.com/a/808850/115145 – CommonsWare Aug 14 '13 at 11:47
  • Beyond that, since you have the HTML as a `String`, you can parse out the comment yourself if you wanted. – CommonsWare Aug 14 '13 at 11:50
  • @CommonsWare I know it's a very old habit, but it's just how this web service returns it. Also, it seems like a very common habit, so I find it weird that the `WebView` fails so badly with it, especially when the browser app handles it properly. And I'd rather stay away from string parsing, seems very hackish in this situation :). – Felix Aug 14 '13 at 12:37
  • I doubt that you're going to have much option other than the string parsing approach. You're welcome to file an issue on it -- I didn't see one when I searched -- and perhaps you'll get an official statement about it. – CommonsWare Aug 14 '13 at 12:59
  • @CommonsWare [done](https://code.google.com/p/android/issues/detail?id=58969). Feel free to add an answer so I can mark it as accepted. – Felix Aug 14 '13 at 13:31

1 Answers1

2

On the whole, the put-the-JavaScript-in-comments trick appears to be no longer the recommended pattern, and so I'd encourage you to reconsider your plan to keep serving it that way.

You have obviously enabled JavaScript in the WebView, otherwise it would not work when you tried removing the comments. I know of no other setting to tell WebView to to ignore the comment markers.

You're welcome to examine the AOSP Browser code to try to find out what they do, though that code is nasty, brutish, and long. You could patch up the HTML before handing it to the WebView. You could set a particular user agent on the WebView and have your Web service hand back cleaned-up HTML for that user agent, leaving the rest of your Web service clients unaffected. And you can see if you get a response to your bug report, though there's no assurance of getting such a response.

Beyond that, I'm out of ideas.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491