简体   繁体   中英

Why does Android WebView reset JavaScript context on second page load?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM