15

In an iOS app, I used

stringFromJavaScript = [webView stringByEvaluatingJavascriptFromString:@"document.getElementById(\"image\").getAttribute(\"src")"];

To get the src directory of the image that was being displayed on the webView. I want to do the same for Android. What are my options?

Basically the intent is to capture the path so that I can email this same picture...

ie.

"picture.php?image=%@",stringFromJavascript

This way, that same image would be loaded when the user clicks the link, or posts it to facebook etc.

rjfellman
  • 175
  • 2
  • 8
  • Something like this may be the right track, however I would like to get the element as a String to use in the code http://lexandera.com/2009/01/injecting-javascript-into-a-webview/ – rjfellman Apr 24 '12 at 20:33
  • The silly part is that `WebView.loadURL()` apparently uses `stringByEvaluatingJavascriptFromString()` internally when the URL scheme is `javascript`. https://github.com/android/platform_frameworks_base/blob/master/core/java/android/webkit/BrowserFrame.java#L262 – JAB Jun 20 '13 at 18:28
  • You could use this method in Android via reflection, please visit http://stackoverflow.com/a/17830417/2442753 – Jonny Chen Jul 24 '13 at 09:58

1 Answers1

38

Yeah, I miss this method greatly in Android ;)

To execute JavaScript and get response you can do as follows:

  1. Define JavaScript callback interface in your code:

    class MyJavaScriptInterface {
        @JavascriptInterface
        public void someCallback(String jsResult) {
             // your code...
        }
    }
    
  2. Attach this callback to your WebView

    MyJavaScriptInterface javaInterface = new MyJavaScriptInterface();
    yourWebView.addJavascriptInterface(javaInterface, "HTMLOUT");
    
  3. Run your JavaScript calling window.HTMLOUT.someCallback from the script:

    yourWebView.loadUrl("javascript:( function () { var resultSrc = document.getElementById(\"image\").getAttribute(\"src\"); window.HTMLOUT.someCallback(resultSrc); } ) ()");
    

Hope this helps!

Lachlan Goodhew-Cook
  • 1,101
  • 17
  • 31
Łukasz Sromek
  • 3,637
  • 3
  • 30
  • 43
  • 1
    thank you so much! this works fantastic! too bad its so much more tedious than the iOS method! Though i suppose a bit more flexible! :) – rjfellman Apr 27 '12 at 20:39
  • +1 because you explained the idea clearly, i could not understand the concept from the other websites... – TMMDev Jun 15 '14 at 12:04
  • 2
    Hi,i am getting Uncaught TypeError, please check the error.[INFO:CONSOLE(1)] "Uncaught TypeError: Cannot call method 'someCallback' of undefined", source: (1) – Ravikumar11 Jul 16 '14 at 04:51