javascript - Android WebView using loadDataWithBaseURL the loaded document imports additional scripts, but they aren't ran -
problem:
- for android webview, need html doc downloaded cdn.
- i need periodically re-download document see if it's been updated.
- i want webview load document, load new version if different current version preserve page variables (i have no influence on document , cannot change way runs).
my solution natively load document using httpurlconnection , use webview.loaddatawithbaseurl(...). way can diff document versions , call method when there's new document. also, document can fetch additional resources using baseurl.
webview.getsettings().setjavascriptenabled(true); webview.setwebchromeclient(new webchromeclient(){ /*...*/ }); webview.setwebviewclient(new webviewclient(){ /*...*/ }); string html = gethtmldoc("http://somecdn.com/doc.html"); webview.loaddatawithbaseurl("http://somecdn.com/", html, "text/html", "utf-8", null);
the unexpected behavior:
d/console(xxxx): onpagestarted:http://somecdn.com/doc.html d/console(xxxx): onloadresource:http://somecdn.com/script.js d/console(xxxx): onpagefinished:http://somecdn.com/doc.html
but when call:
webview.loadurl("javascript:console.log(typeof some_object)");
where some_object defined in script.js, following printed:
d/console(xxxx): undefined
there no errors being reported webviewclient.onreceivederror(...). missing? there better means of loading doc.html if there's new version? don't have access cdn outside of downloading content. testing on android 4.1.1 need support froyo-kitkat+
edit:
solution:
per marcin.kosiba's recommendation, i'm going use head request if-modified-since
specified:
simpledateformat ifmodifiedformat = new simpledateformat("eee, dd mmm yyyy hh:mm:ss 'gmt'", locale.us); ifmodifiedformat.settimezone(timezone.gettimezone("gmt")); final httpurlconnection conn = (httpurlconnection)(new url("http://somecdn.com/doc.html")).openconnection(); conn.setrequestmethod("head"); conn.setrequestproperty("if-modified-since", ifmodifiedformat.format(new date(/* last fetched date */))); conn.setrequestproperty("accept-encoding", "*"); conn.connect(); if(conn.getresponsecode() == 200) { webview.reload(); }
there bug head requests in android eofexception
thrown, adding conn.setrequestproperty("accept-encoding", "*");
or conn.setrequestproperty("accept-encoding", "");
resolves issue.
since need reload page in webview anyway, instead of downloading html ask server if had changed , if has ask webview reload it? see answer https://stackoverflow.com/a/1938603/2977376 how use if-modified-since
ask server if contents had changed.
Comments
Post a Comment