Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringByEvaluatingJavascriptFromString (iOS method, what is Android equivalent?)

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.

like image 689
rjfellman Avatar asked Apr 24 '12 19:04

rjfellman


1 Answers

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!

like image 83
Łukasz Sromek Avatar answered Oct 20 '22 15:10

Łukasz Sromek