[英]load and execute a script in android and ios
My requirements: 我的要求:
What are my options? 我有什么选择?
WebView Android with Javascript Enabled 启用了Javascript的WebView Android
SFWebView i think in iOS also support Javascript. 我认为SFWebView在iOS中也支持Javascript。
Not sure that you can use it in background thread as Android Webview will only runs on UI thread 不确定您可以在后台线程中使用它,因为Android Webview仅在UI线程上运行
Answer: 1. You MUST load the HTML into string: 答案:1.您必须将HTML加载到字符串中:
private String readHtml(String remoteUrl) {
String out = "";
BufferedReader in = null;
try {
URL url = new URL(remoteUrl);
in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
out += str;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out;
}
Load WebView with base URL: 使用基本URL加载WebView:
String html = readHtml("Your Web URL"); mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");
In this particular case you should have all .js files you want to use on the page to reside somewhere under "assets" folder of project. 在这种情况下,您应该将要在页面上使用的所有.js文件都放置在项目的“ assets”文件夹下的某个位置。 For example:
例如:
/MyProject/assets/jquery.min.js
In your remote html page you have to load .js and .css files that reside in your application like: 在远程html页面中,您必须加载驻留在应用程序中的.js和.css文件,例如:
the same applies to all other local resources like images, etc. their path has to start with 这同样适用于所有其他本地资源,例如图像等。其路径必须以
file:///android_asset/
A WebView would first load the raw HTML you have provided as string, then pick .js, .css and other local resourses and then would load remote content. WebView首先会加载作为字符串提供的原始HTML,然后选择.js,.css和其他本地资源,然后加载远程内容。
In android, While loading the page into webview. 在android中,将页面加载到webview中。 Intercept the script call.
拦截脚本调用。
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if ( url.endsWith("script.js") ) {
AssetFileDescriptor fileDescriptor = assetManager.openFd("script.js");
FileInputStream stream = fileDescriptor.createInputStream();
return new WebResourceResponse("text/javascript","UTF-8",stream);
}
}
Webview runs on ui thread. Webview在ui线程上运行。 I am not sure that there is way to load webresources from background threads.
我不确定是否有从后台线程加载Web资源的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.