stringByEvaluatingJavascriptFromString (iOS method, what is Android equivalent?)
Asked Answered
Q

1

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.

Quern answered 24/4, 2012 at 19:27 Comment(3)
Something like this may be the right track, however I would like to get the element as a String to use in the code lexandera.com/2009/01/injecting-javascript-into-a-webviewQuern
The silly part is that WebView.loadURL() apparently uses stringByEvaluatingJavascriptFromString() internally when the URL scheme is javascript. github.com/android/platform_frameworks_base/blob/master/core/…Shaynashayne
You could use this method in Android via reflection, please visit https://mcmap.net/q/822349/-exist-stringbyevaluatingjavascriptfromstring-for-androidWeinberg
P
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!

Penchant answered 27/4, 2012 at 11:8 Comment(3)
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! :)Quern
+1 because you explained the idea clearly, i could not understand the concept from the other websites...Banks
Hi,i am getting Uncaught TypeError, please check the error.[INFO:CONSOLE(1)] "Uncaught TypeError: Cannot call method 'someCallback' of undefined", source: (1)Tuna

© 2022 - 2024 — McMap. All rights reserved.