My code is as follow:
myWebView = new WebView(this);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setUserAgentString("iTunes-AppleTV/5.1 (3; 8GB; dt:12)");
System.out.println(android.os.Build.VERSION.SDK_INT);
if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}
myWebView.setWebChromeClient(new WebChromeClient());
js_url_string =
" var script=document.createElement('script'); "
+ " script.setAttribute('type','text/javascript'); "
+ " script.setAttribute('src', 'http://trailers.apple.com/appletv/us/js/application.js'); "
+ " script.onload = function() { "
+ " var req = new XMLHttpRequest(); "
+ " var req_cnt = 0; "
+ " req.onreadystatechange = function() { "
+ " try { "
+ " gtkTV.dump(req.readyState); "
+ " "
+ " if(req.readyState == 4) { "
+ " if(req.status == 200) { "
+ " if (req_cnt == 1) {"
+ " var url = req.responseText.match(/http:.*js/); "
+ " req.open('GET', url, true); "
+ " req.send(null); "
+ " req_cnt += 1; "
+ " } "
+ " else if (req_cnt == 2) { "
+ " gtkTV.loadXML(gtkTV.parseXML(req.responseText)); "
+ " } "
+ " else { "
+ " gtkTV.dump('Unknown request'); "
+ " } "
+ " } "
+ " else { "
+ " gtkTV.dump(req.statusText); "
+ " } "
+ " } "
+ " } "
+ " catch(e){ "
+ " req.abort(); "
+ " gtkTV.dump('Loadpage error!'); "
+ " } "
+ " }; "
+ " gtkTV.dump(atv.config.ROOT_URL); "
+ " req.open('GET', atv.config.ROOT_URL, true); "
+ " req.send(null); "
+ " req_cnt += 1; "
+ " }; "
+ " document.getElementsByTagName('head')[0].appendChild(script); ";
myWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:(function() { "
+ " document.getElementByTagName = function(id) {"
+ " return document.getElementsByTagName(id);"
+ " };"
+ js_url_string
+ "})()");
}
});
myWebView.addJavascriptInterface(new MyAndroidJSInterface(this, MainActivity.class), "gtkTV");
myWebView.loadUrl("file:///android_asset/tmp.html");
My goal was to make script tag work for src to send request and include an external JS with a custom User-Agent value. Unfortunately after I did some research on the internet, I could not find a solution for it and people always say it's not a bug but not allowed by FF. At the moment when I was planning to give up and tried some other ugly ways to do that, I found a post at the reference link and realized Damn! that I was using WebView and there are some methods I could use to do that ! Better late than never, ugh.
Reference links
http://developer.android.com/guide/webapps/webview.html
沒有留言:
張貼留言