2
votes

I am using an Android WebView with local data by first setting up a JavaScript environment and then loading web content that relies on the existence of the JavaScript environment:

test.js:

alert("test.js: type of window.myVar is: " + (typeof window.myVar));
window.myVar = {};

test.html:

<!DOCTYPE>
<html><head>
<script>
alert("test.html: type of window.myVar is: " + (typeof window.myVar));
</script>
</head><body></body></html>

loading procedure in Java:

private void loadData() {
    _webView.loadUrl("javascript:" + testJSContent);
    _webView.loadDataWithBaseURL(null, testHTMLContent, "text/html", "utf-8", null);
}

The first time loadData() is triggered, window.myVar is available from the loaded HTML page, but undefined on any subsequent tries. Here is the alert output on three invokations:

-> loadData() called
"test.js: type of window.myVar is: undefined"
"test.html: type of window.myVar is: object"
-> loadData() called
"test.js: type of window.myVar is: object"
"test.html: type of window.myVar is: undefined"
-> loadData() called
"test.js: type of window.myVar is: undefined"
"test.html: type of window.myVar is: undefined"


Any ideas why the JavaScript object created by injection is only persistent until the second page load?

Thanks for any help!

1
afaik, every page loaded has its own javascript variables. If it wouldn't be like this, you could do XXS within your browser history...! it's not a matter of android-webview javascript in general, but maybe I misunderstood the problem - lelloman
Good point indeed. But since setting up a JS context like this works for the first page load, do you know if there is any way to reset the WebView back to the initial state and re-enable JS injection? - user2174643
something like myWebView.goBack()? I don't understand why you need to put javascript and html in two separated steps - lelloman
This procedure is used within an Android SDK library where in-SDK JavaScript code has to be included into HTML markup retrieved from an external server. - user2174643
I still don't understand the need of loading content (js, html or whatever) two times...can't you just merge them and load just once? - lelloman

1 Answers

0
votes

You should first load the html and after that page has fully loaded inject the javascript. Do it in OnPageFinished of the WebViewClient.