-1

I need to pull a JavaScript var off a site so I can use it in my code. Following this tutorial, I was able to display the string in an alert message. But what do I have to do to use the string outside of the alert message? Thanks.

EDIT: My code is basically the same as in the tutorial.

2
  • Please post the code you used to display the alert message.
    – gilly3
    Nov 3, 2011 at 21:58
  • It's basically the same as in the tutorial I linked.
    – gamma
    Nov 3, 2011 at 21:59

1 Answer 1

0

Instead of calling AlertDialog, just do something in Java with the value of the "html" parameter, unless I'm completely misunderstanding what you are asking.

String savedHtml = null;

/* An instance of this class will be registered as a JavaScript interface */  
class MyJavaScriptInterface  
{  
    @SuppressWarnings("unused")  
    public void showHTML(String html)  
    {  
        savedHtml = html; // this ought to work.
    }  
}  
6
  • This is the first thing I tried, but it doesn't work. The string is always empty. I guess it's because it's the JS Interface calling the method, not my actual code?
    – gamma
    Nov 3, 2011 at 22:20
  • addJavascriptInterface registers the actual Java object as a Javascript object within the web page. Calling the method in Javascript is equivalent to calling it in Java. There must be something else going on here. What does your code look like when you try to set an instance variable instead of creating the dialog? Or have you tried something simple like System.out.println?
    – Scott A
    Nov 3, 2011 at 22:33
  • It looks like your example. I just tried it again though. "savedHtml = html" does work after all. The problem seems to be that the code continues after "browser.loadUrl". I figured onPageFinished would be called immediately after that. But it looks like all code in the onCreate method is executed before that, is that correct?
    – gamma
    Nov 3, 2011 at 23:12
  • onPageFinished won't fire until the page is completely loaded, so it's asynchronous to when you actually start loading it. If you want to do something with the data generated by the callback, do it in the callback itself.
    – Scott A
    Nov 3, 2011 at 23:24
  • I see, thanks. Is that the conventional way of doing that? Shouldn't showHTML just do what it's supposed to do (get the data) and nothing more?
    – gamma
    Nov 3, 2011 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.