The webview injection of JS code into Android can be implemented by Webview.loadurl ("Javascript:xxx"), and then the code behind the JavaScript is executed.
But when a whole JS file needs to be injected, it looks like a bit of a hassle.
But clear the following ideas, the method is actually very simple, as follows:
We do this by executing JS code injection in the WebView onpagefinished method:
The first type:
When WebView is loaded, the contents of the entire JS file are read, and the entire file content is injected as a string, via Webview.loadurl ("javascript:filecontentstring")
URL url =NewURL ("Http://www.rayray.ray/ray.js"); in=Url.openstream ();byteBuff[] =New byte[1024]; Bytearrayoutputstream FromFile=NewBytearrayoutputstream (); FileOutputStream out=NULL; Do { intNumread =in.read (Buff); if(Numread <= 0) { Break; } fromfile.write (Buff,0, Numread); } while(true); String Wholejs= Fromfile.tostring ();
@Override Public void onpagefinished (WebView view, String URL) { super. onpagefinished (view, URL); Webview.loadurl ("javascript:" + Wholejs);}
The second type:
After the page is loaded, add the <script> note to the HTML corresponding to the WebView, and include the URL address of the JS to be injected, as follows:
String js = "var newscript = document.createelement (\" script\ ");" + = "newscript.src=\" http://www.123.456/789.js\ ";" + = "Document.body.appendChild (newscript);";
Public void onpagefinished (WebView view, String URL) { super. onpagefinished (view, URL); Webview.loadurl ("javascript:" + js); }
PostScript: In the above two ways, the second method is simpler and more convenient. However, the second method also has a problem, when you inject the JS after you want to call the method immediately, the first method is no problem can be called to. But the second method, you want to ensure that the injected <script> note corresponding to the JS file is loaded before the call succeeds.
Workaround: Add the OnLoad event in the second method for adding the script tag to ensure that the script is 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 ();};"; // xxx () represents a method in JS JS + = "Document.body.appendChild (newscript);";
Also in iOS, follow the same idea and then in-(void) Webviewdidfinishload: (UIWebView *) WebView using [WebView stringbyevaluatingjavascriptfromstring:@ "xxx"];
This article transferred from: http://www.cnblogs.com/rayray/p/3680500.html
WebView JavaScript Injection method