I’m trying to write a class that will return a string of HTML with Javascript for use in a WebView. Returning HTML and Javascript works well, but I’m having issues loading libraries with the returned HTML. As an example, this works well:
public static String helloWorld() {
String html;
html = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<title>" +
"</title>" +
"</head>" +
"<body>" +
"<script>" +
"document.write(\"Hello, World\");" +
"</script>" +
"</body>" +
"</html>";
return html;
}
However, this does not:
public static String helloWorld() {
String html;
html = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<title>" +
"</title>" +
"<script src=\"../assets/src/external_script.js\"></script>" +
"</head>" +
"<body>" +
"<script>" +
"external_script_function();" +
"</script>" +
"</body>" +
"</html>";
return html;
}
I’m guessing that the filepath for the external_script.js import is incorrect? Using WebView.LoadUrl(myLocalHtmlFile); works when using the other JS file. How would I go about making this work properly? Or alternatively, is there a better way to achieve similar results?
You need to feed the assets folder to the WebView as the base URL. Like this:
And then the
<script>tag would go like this:Assuming the library resides under
assets/src. And yes, you need to enable JavaScript like triad is suggesting.