1

I'm trying to do something a little tricky. I have an activity which has a webView inside. This web view is loading an external html file which has some javascript functions.

My activity is producing some reults periodically and I want to access these results in javascript functions. I thought writing output results to a file and reading in javascript side might be a solution. But I'm not sure about it.

Is there a way for doing sth like this ?

I know that we can navigate to android functions from javascript, but it is not exactly what I need.

Thanks..

penguru
  • 4,342
  • 11
  • 46
  • 56
  • not sure if JS can read files stored locally – suraj jain Apr 10 '12 at 08:56
  • js can read local files. You could place the js files into the assets folder of your app as well as the file to read and it will do it. My app does this to get satellite position, calculations done in the js are then read by my android web view and displayed on screen – Katana24 Apr 10 '12 at 09:13
  • @Katana24 actually I'm trying to do exactly same thing. Getting gps position and showing on a map. But as I know, I cannot write to a file in asset folder? – penguru Apr 10 '12 at 09:44
  • Not the asset folder (or anywhere in the app itself), but the local file storage directory. – Sparky Apr 10 '12 at 09:58
  • So correct me if Im wrong - your activity gets the lat and long of something and writes them to a file. Then you want a javascript file to read from that file right? – Katana24 Apr 10 '12 at 10:13
  • @Katana24, it's what I want. – penguru Apr 10 '12 at 10:15

1 Answers1

2

If you need the results only once, and on the fly, then you could try not to write them to a file but to inject it to the WebView as javascript. For example in your page you could add a function:

function newData(jsonObj) {
    ...
}

and instead of writing to a file you would call this with your actual data.

webview.loadUrl("javascript:(newData({a:1, b:2,...}))");  
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • How can I call javascript function from android activity and inject jsonObj parameter? – penguru Apr 10 '12 at 10:16
  • added an example to the answer – Gavriel Apr 10 '12 at 10:22
  • @Flöcys - I'm not ure if it will work. Because I already loading webview with webView.loadDataWithBaseURL. Then calling loadUrl again might not work. I'll try.. – penguru Apr 10 '12 at 10:45
  • 1
    according to http://stackoverflow.com/questions/5064646/android-injecting-javascript-into-a-webview-outside-the-onpagefinished-event and http://stackoverflow.com/questions/4932920/injecting-javascript-into-a-webview-outside-the-onpagefinished-event-using-date it should work – Gavriel Apr 10 '12 at 10:51
  • Thank you very much, it works very well! It's definitely better solution than using temporary file. – penguru Apr 10 '12 at 12:20