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,081
  • 17
  • 30
Łukasz Sromek
  • 3,567
  • 3
  • 29
  • 43