2

I have a JavaScript script that looks for the location of an element in page using jQuery in a loaded WebView.

For some reason this script works only sometimes and I suspect that it's related to the time it takes to load the script or maybe the page. I'm trying to evaluate the script only on onPageFinished of the WebViewClient interface, So I don't think that the loading of the page has something to do with it, but maybe I'm wrong.

I am an Android developer and have a very limited understanding in JavaScript and jQuery but I know the script works because the same script is used in the iOS platform and returns good results always.

Chances are there is some timing problem with loading the script itself.

So the question is: Is there a way to load the script before its usage, or load it and make sure it loaded into the WebView.

halfer
  • 19,824
  • 17
  • 99
  • 186
Emil Adz
  • 40,709
  • 36
  • 140
  • 187
  • 2
    If you want the script to run when the page finishes loading, in the html before the

    tag put a script tag with this code inside: $(document).ready(function(){ });

    – Juan Jun 06 '17 at 12:36
  • @Juan The problem is that the page I'm loading into the WebView is not my page. I have no control over the html or the javascript content that is loaded in the WebView except the script I'm adding/evaluating that contains some logic regarding finding specified elements in the page. – Emil Adz Jun 06 '17 at 12:39
  • Have you tried this: https://stackoverflow.com/questions/21552912/android-web-view-inject-local-javascript-file-to-remote-webpage – Juan Jun 07 '17 at 04:05

1 Answers1

0

Scripts are loaded whenever you call the script tag . They stay loaded until that page is destroyed. They are reachable by any page.

If my thoughts are right, I believe the direct answer for your question is YES. However you would like to know is HOW.

In a webpage you can check if the script is loaded with jQuery, put that piece of code in the end of your

$(function() { 
  //anything here is executed after page is loaded 
});

If you are trying to execute a javascript over a page you don't have control of it's source, I'm afraid you can't do what you want, because of security rules of web standards... You would have to hack it someway I can't help.

Emil Adz
  • 40,709
  • 36
  • 140
  • 187
Ramon Marques
  • 3,046
  • 2
  • 23
  • 34