Javascript code injection to webview in Android can be implemented through webview. loadUrl ("javascript: xxx"), and then the Code following javascript is executed.
However, when you need to inject an entire js file, it seems a little troublesome.
However, to clarify the following ideas, the method is actually very simple, as follows:
We execute js code injection in the onPageFinished method of webview:
First:
After the webview is loaded, read the content of the entire js file and inject the content of the entire file in the form of a string through webview. loadUrl ("javascript: fileContentString ")
URL url = URL("http://www.rayray.ray/ray.js"= buff[] = [1024= = numread = (numread <= 00 (= fromFile.toString();
"javascript:" +
Second:
After the page is loaded, add the <script> tab directly to the html corresponding to webview and include the Url of the js to be injected, as shown below:
String js = "var newscript = document.createElement(\"script\");"+= "newscript.src=\"http://www.123.456/789.js\";"+= "document.body.appendChild(newscript);";
"javascript:" +
Note: In the above two methods, the second method is simpler and more convenient. However, the second method also has a problem. When you inject Javascript, you want to call the method immediately. The first method can be called without any problems. However, in the second method, make sure that the js file corresponding to the injected <script> tab is successfully loaded.
Solution: In the second method, add an onload event to the script tag to ensure that the script has been loaded. The code can be changed as follows:
String js = "var newscript = document.createElement(\"script\");"+= "newscript.src=\"http://www.123.456/789.js\";"+= "newscript.onload=function(){xxx();};"; js += "document.body.appendChild(newscript);";
The same is true for IOS. Use [webView stringByEvaluatingJavaScriptFromString: @ "xxx"]; In-(void) webViewDidFinishLoad :( UIWebView.