下面列出了怎么用android.webkit.WebViewClient的API类实例代码及写法,或者点击链接到github查看源代码。
public TaskAddHtml(WebView webview, HttpFinishCallBack callBack) {
this.callBack = callBack;
List<MapConfigBean> list = LitePal.findAll(MapConfigBean.class);
List<String> name = new ArrayList<>();
for (MapConfigBean m : list) {
name.add(m.name);
}
webview.loadUrl("file:///android_asset/html/task.html");
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl(String.format("javascript:onLoad(\'%s\')", JSON.toJSONString(name)));
}
});
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Ignore error due to stopLoading().
if (!isCurrentlyLoading) {
return;
}
LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// If this is a "Protocol Not Supported" error, then revert to the previous
// page. If there was no previous page, then punt. The application's config
// is likely incorrect (start page set to sms: or something like that)
if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) {
parentEngine.client.clearLoadTimeoutTimer();
if (view.canGoBack()) {
view.goBack();
return;
} else {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
parentEngine.client.onReceivedError(errorCode, description, failingUrl);
}
public void initWebView(String data) {
WebView mWebView = findViewById(R.id.showdiarys);
WebSettings settings = mWebView.getSettings();
//settings.setUseWideViewPort(true);//调整到适合webview的大小,不过尽量不要用,有些手机有问题
settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
mWebView.setVerticalScrollBarEnabled(false);//不能垂直滑动
mWebView.setHorizontalScrollBarEnabled(false);//不能水平滑动
settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings,改变HTML中文字的大小
settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
//设置WebView属性,能够执行Javascript脚本
mWebView.getSettings().setJavaScriptEnabled(true);//设置js可用
mWebView.setWebViewClient(new WebViewClient());
mWebView.addJavascriptInterface(new AndroidJavaScript(getApplication()), "android");//设置js接口
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
mWebView.loadUrl(data);
}
private void initWebView() {
if (this.mWebView == null) {
this.mWebView = new WebView(this);
this.mWebView.setBackgroundColor(-1);
this.rootView.addView(this.mWebView, new LayoutParams(-1, -1));
this.mWebView.getSettings().setUseWideViewPort(true);
this.mWebView.getSettings().setSupportZoom(true);
this.mWebView.getSettings().setBuiltInZoomControls(true);
this.mWebView.setVerticalScrollBarEnabled(true);
this.mWebView.setHorizontalScrollBarEnabled(true);
this.mWebView.getSettings().setJavaScriptEnabled(true);
this.mWebView.getSettings().setDomStorageEnabled(true);
this.mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
AlbumPlayActivity.this.mWebView.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
this.mWebView.setClickable(false);
}
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//noinspection ConstantConditions
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.presentation_activity);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.loadUrl("file:///android_asset/slides/index.html");
}
private void setClient() {
web.setWebChromeClient(new WebChromeClient() {
});
// 如果要自动唤起自定义的scheme,不能设置WebViewClient,
// 否则,需要在shouldOverrideUrlLoading中自行处理自定义scheme
// webView.setWebViewClient();
web.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
@SuppressLint("SetJavaScriptEnabled")
@Provides
@Singleton
static WebView providesWebView(@ApplicationContext Context context){
Logger.t(TAG).d("初始化");
WebView mWebView = new WebView(context);
WebSettings mWebSettings = mWebView.getSettings();
//启用JavaScript。
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setUseWideViewPort(true);
mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.loadUrl("file:///android_asset/web/index.html"); //js文件路径
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
Logger.t(TAG).d("加载完成..:" + url);
}
});
return mWebView;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mWebview = (WebView) view.findViewById(R.id.h5_web);
WebSettings webSettings = mWebview.getSettings();
webSettings.setSupportZoom(false);
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setLoadWithOverviewMode(true);
webSettings.setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebViewClient(new WebViewClient());
mWebview.loadUrl(mUrl);
DetailAnimViewGroup wrapper = new DetailAnimViewGroup(inflater.getContext(), view, 0);
wrapper.setReversed(false);
return wrapper;
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.cancel();
// WebView can try to load the favicon for a bad page when you set a new URL. If we then
// loadErrorPage() again, WebView tries to load the favicon again. We end up in onReceivedSSlError()
// again, and we get an infinite loop of reloads (we also erroneously show the favicon URL
// in the toolbar, but that's less noticeable). Hence we check whether this error is from
// the desired page, or a page resource:
if (error.getUrl().equals(currentPageURL)) {
TelemetryWrapper.sslErrorEvent(true, error);
ErrorPage.loadErrorPage(view, error.getUrl(), WebViewClient.ERROR_FAILED_SSL_HANDSHAKE);
} else {
TelemetryWrapper.sslErrorEvent(false, error);
}
}
public void resetView() {
setContentView(R.layout.activity_issue_preview);
((TextView) findViewById(R.id.title)).setText(Utils.stripTags(title));
final WebView web = (WebView) findViewById(R.id.detailsLabel);
web.loadDataWithBaseURL(null, details, "text/html", "utf-8", null);
web.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (Exception failed) {
return false;
}
return true;
}
});
}
static void toggleInvisibleInk(final WebView invisibleInkView, final ViewGroup bubble, TextView text, LinearLayout replay){
bubble.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
text.setVisibility(View.GONE);
replay.setVisibility(View.GONE);
invisibleInkView.setVisibility(View.VISIBLE);
String invisibleInk = "<html><head><style type='text/css' rel='stylesheet'> html { margin: 0; padding: 0em; }</style></head><body><span class='ink'>" + text.getText() + "</span> <script src='jquery.js' type='text/javascript'></script> <script src='invisibleink.js' type='text/javascript'></script></body></html>";
invisibleInkView.loadDataWithBaseURL("file:///android_asset/html/", invisibleInk, "text/html", "UTF-8", null);
invisibleInkView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
invisibleInkView.loadUrl("javascript:weMessage.resizeInvisibleInk(document.body.getBoundingClientRect().height)");
super.onPageFinished(view, url);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.about);
webview = (WebView) findViewById(R.id.webvAbout);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http")) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return false;
}
});
webview.loadUrl("file:///android_asset/about.html");
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
@SuppressWarnings("deprecation")
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Ignore error due to stopLoading().
if (!isCurrentlyLoading) {
return;
}
LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// If this is a "Protocol Not Supported" error, then revert to the previous
// page. If there was no previous page, then punt. The application's config
// is likely incorrect (start page set to sms: or something like that)
if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) {
parentEngine.client.clearLoadTimeoutTimer();
if (view.canGoBack()) {
view.goBack();
return;
} else {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
parentEngine.client.onReceivedError(errorCode, description, failingUrl);
}
public void resetView() {
setContentView(R.layout.activity_issue_preview);
((TextView) findViewById(R.id.title)).setText(Utils.stripTags(title));
final WebView web = (WebView) findViewById(R.id.detailsLabel);
web.loadDataWithBaseURL(null, details, "text/html", "utf-8", null);
web.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
try {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (Exception failed) {
return false;
}
return true;
}
});
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Custom WebView");
jsBridge = JsBridge.loadModule();
WebView.setWebContentsDebuggingEnabled(true);
customWebView = new CustomWebView(this);
setContentView(customWebView);
customWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
jsBridge.injectJs(customWebView);
}
});
customWebView.setPromptResult(new PromptResultCallback() {
@Override
public void onResult(String args, PromptResultImpl promptResult) {
jsBridge.callJsPrompt(args, promptResult);
}
});
customWebView.loadUrl("file:///android_asset/sample.html");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView markdownView = (WebView) findViewById(R.id.markdownView);
markdownView.getSettings().setJavaScriptEnabled(true);
markdownView.loadUrl(getResources().getString(R.string.official_remote_url));
markdownView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
MarketingCloudSdk.requestSdk(new MarketingCloudSdk.WhenReadyListener() {
@Override
public void ready(MarketingCloudSdk marketingCloudSdk) {
marketingCloudSdk.getAnalyticsManager().trackPageView("data://OriginalDocsActivity", getResources().getString(R.string.official_remote_url), null, null);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
WebView v_scroll = (WebView)findViewById(R.id.v_scroll);
v_scroll.loadUrl("http://www.github.com/w446108264");
v_scroll.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
private void onErrorDetected(boolean errorHandled, ChatWindowErrorType errorType, int errorCode, String errorDescription) {
progressBar.setVisibility(GONE);
if (!errorHandled) {
if (chatUiReady && errorType == ChatWindowErrorType.WebViewClient && errorCode == -2) {
//Internet connection error. Connection issues handled in the chat window
return;
}
webView.setVisibility(GONE);
statusText.setVisibility(View.VISIBLE);
reloadButton.setVisibility(VISIBLE);
}
}
/**
* Convenience method to set some generic defaults for a
* given WebView
*
* @param webView
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setUpWebViewDefaults(WebView webView) {
WebSettings settings = webView.getSettings();
// Enable Javascript
settings.setJavaScriptEnabled(true);
// Use WideViewport and Zoom out if there is no viewport defined
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
// Enable pinch to zoom without the zoom buttons
settings.setBuiltInZoomControls(true);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
// Hide the zoom controls for HONEYCOMB+
settings.setDisplayZoomControls(false);
}
// Enable remote debugging via chrome://inspect
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
// We set the WebViewClient to ensure links are consumed by the WebView rather
// than passed to a browser if it can
mWebView.setWebViewClient(new WebViewClient());
}
public PWebView(AppRunner appRunner) {
super(appRunner.getAppContext());
mAppRunner = appRunner;
styler = new Styler(appRunner, this, props);
// styler.apply();
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
WebSettings webSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
this.setFocusable(true);
this.setFocusableInTouchMode(true);
this.clearCache(false);
this.setBackgroundColor(0x00000000);
this.requestFocus(View.FOCUS_DOWN);
this.setOnTouchListener((v, event) -> {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
});
WebViewClient webViewClient = new CustomWebViewClient();
this.setWebViewClient(webViewClient);
this.addJavascriptInterface(mAppRunner.pApp, "app");
}
@Override
public void onResume() {
super.onResume();
showProgressBar();
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
hideProgressBar();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
String url = getIntent().getStringExtra(EXTRA_URL);
WebView webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
setTitle(url);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webView.loadUrl(url);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final CordovaActivity me = this;
// If errorUrl specified, then load it
final String errorUrl = preferences.getString("errorUrl", null);
if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit) {
me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
}
});
}
}
private void defInit()
{
getSettings().setSupportZoom(true);
getSettings().setBuiltInZoomControls(true);
getSettings().setDisplayZoomControls(false);
getSettings().setUseWideViewPort(false);
getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
getSettings().setAllowFileAccess(true);
getSettings().setJavaScriptEnabled(true);
setWebViewClient(
new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
if(url.endsWith(".log"))
postDelayed(
new Runnable()
{
@Override
public void run()
{
if(Thread.interrupted()) return;
if(getContentHeight() == 0)
postDelayed(this, 100);
else
scrollToBottom();
}
}, 500);
}
});
}
private void initWebView() {
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setSupportZoom(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
/**
* Package private for testing.
*/
void setUpWebView(WebView webView, WebViewClient webViewClient, String url,
WebChromeClient webChromeClient) {
final WebSettings webSettings = webView.getSettings();
webSettings.setAllowFileAccess(false);
webSettings.setJavaScriptEnabled(false);
webSettings.setSaveFormData(false);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(webViewClient);
webView.loadUrl(url);
webView.setVisibility(View.INVISIBLE);
webView.setWebChromeClient(webChromeClient);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final CordovaActivity me = this;
// If errorUrl specified, then load it
final String errorUrl = preferences.getString("errorUrl", null);
if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit) {
me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
}
});
}
}
private void initWebView() {
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
swipeRefreshLayout.setRefreshing(false);
if (contentLayout != null)
contentLayout.showContent();
if (webView != null)
url = webView.getUrl();
} else {
if (contentLayout != null)
contentLayout.showLoading();
}
}
});
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
webView.loadUrl(url);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (NullPointerException e) {
e.printStackTrace();
}
// Web view
WebView webView = (WebView)findViewById(R.id.mainWebView);
WebSettings webSettings = webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
// other
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
// important!
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/help/index.html");
}
@Override
public void setWebViewClient(WebViewClient client) {
if (mFastClient != null) {
mFastClient.updateProxyClient(client);
} else {
super.setWebViewClient(client);
}
mUserWebViewClient = client;
}