Особенности использования WebView в Android-приложениях
In Android, WebView is a view used to display the web pages in application. This class is the basis upon which you can roll your own web browser or simply use it to display some online content within your Activity. We can also specify HTML string and can show it inside our application using a WebView. Basically, WebView turns application into a web application.
In order to add Web View in your application, you have to add element to your XML( layout ) file or you can also add it in java class.
Internet Permission Required For Webview:
Important Note: In order for Activity to access the Internet and load the web pages in a WebView, we must add the internet permissions to our Android Manifest file (Manifest.xml).
Below code define the internet permission in our manifest file to access the internet in our application.
Methods of WebView In Android:
Let’s discuss some common methods of a Webview which are used to configure a web view in our application.
loadUrl() – Load a web page in our WebView
loadUrl(String url)
This function is used to load a web page in a web view of our application. In this method we specify the url of the web page that should be loaded in a web view.
Below we load a url: https://abhiandroid.com/ui/ in our application.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);
// specify the url of the web page in loadUrl function
simpleWebView.loadUrl(«https://abhiandroid.com/ui/»);
2. loadData() – Load Static Html Data on WebView
loadData(String data, String mimeType, String encoding)
This method is used to load the static HTML string in a web view. loadData() function takes html string data, mime-type and encoding param as three parameters.
Below we load the static Html string data in our application of a web view.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
WebView webView = (WebView) findViewById(R.id.simpleWebView);
// static html string data
String customHtml = »
Hello, AbhiAndroid
» +
»
Heading 1
Heading 2
Heading 3
» +
«
This is a sample paragraph of static HTML In Web view
» +
«»;
// load static html data on a web view
webView.loadData(customHtml, «text/html», «UTF-8»);
3. Load Remote URL on WebView using WebViewClient:
WebViewClient help us to monitor event in a WebView. You have to Override the shouldOverrideUrlLoading() method. This method allow us to perform our own action when a particular url is selected. Once you are ready with the WebViewClient, you can set the WebViewClient in your WebView using the setWebViewClient() method.
Below we load a url by using web view client in a WebView.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a web view
simpleWebView = (WebView) findViewById(R.id.simpleWebView);
// set web view client
simpleWebView.setWebViewClient(new MyWebViewClient());
// string url which you have to load into a web view
String url = «https://abhiandroid.com/ui/»;
simpleWebView.getSettings().setJavaScriptEnabled(true);
simpleWebView.loadUrl(url); // load the url on the web view
}
// custom web view client class who extends WebViewClient
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // load the url
return true;
}
4. canGoBack() – Move to one page back if a back history exist
This method is used to specify whether the web view has a back history item or not. This method returns a Boolean value either true or false. If it returns true then goBack() method is used to move one page back.
Below we check whether a web view has back history or not.
// initiate a web view WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a back history item or not
Boolean canGoBack=simpleWebView.canGoBack();
5. canGoForward() – Move one page forward if forward history exist
This method is used to specify whether the web view has a forword history item or not. This method returns a Boolean value either true or false. If it returns true then goForword() method is used to move one page forword.
Below we check whether a web view has forward history or not.
// initiate a web view
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);
// checks whether a web view has a forward history item or not
Boolean canGoForword=simpleWebView.canGoForward() ;
- 6. clearHistory() – clear the WebView history
- This method is used to clear the web view forward and backward history.
- Below we clear the forword and backword history of a WebView.
WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView); // initiate a web view
simpleWebView.clearHistory(); // clear the forward and backward history
WebView Example In Android Studio:
Here in this WebView example we show the use of web view in our application. To do that we display two buttons one is for displaying a web page and other is for displaying static HTML data in a web view. Below is the final output, download code and step by step explanation:
Download Code ?
Step 1: Create a new project and name it WebViewExample
Select File -> New -> New Project… then Fill the forms and click «Finish» button.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code :
In this step we open an XML file and add the code for displaying two buttons and a Webview in our xml file ( layout ).
Step 3: Open src -> package -> MainActivity.java
How to Use WebView in Android?
WebView is a view that displays web pages inside the application. It is used to turn the application into a web application.
public class WebView extends AbsoluteLayout implements
ViewTreeObserver.OnGlobalFocusChangeListener,
ViewGroup.OnHierarchyChangeListener
Class Hierarchy:
java.lang.Object
↳ android.view.View
↳ android.view.ViewGroup
↳ android.widget.AbsoluteLayout
↳ android.webkit.WebView
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.
import android.os.Bundle;
setContentView(R.layout.activity_main); WebView webView = findViewById(R.id.web); webView.loadUrl(«https://www.geeksforgeeks.org»); webView.getSettings().setJavaScriptEnabled(true);
|
import android.os.Bundle
setContentView(R.layout.activity_main) val webView = findViewById(R.id.web) webView.loadUrl(«https://www.geeksforgeeks.org») webView.settings.javaScriptEnabled = true
|
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Step 4: Adding Permissions to the AndroidManifest.xml File
In AndroidManifest.xml, one needs to include the below permission, in order to access the internet
Output:
- Last Updated : 08 May, 2023
Working with WebView: displaying web content inside your Android app
When it comes to displaying content inside your Android apps, you’re spoilt for choice, as the Android platform supports a wide range of content – including content pulled straight from external web pages.
There’s many reasons why you might want to display web content inside your latest Android project. Maybe you need to display some complicated data from an external website – instead of going to all that effort of retrieving, processing and then formatting this data, you may decide that it’s easier to simply embed the web page itself in your application’s layout.
Or, maybe you have content that requires frequent updates, such as your company blog, your app’s user manual, or your terms and conditions.
If you hard-code this content into your app, then the only way you can update it is by releasing a new version of that app.
However, if you host this content online and then display the hosted version inside your app, then you’re free to update this content whenever you want and those changes will appear in your app automatically.
In this tutorial I’ll show you exactly how to embed web content in your Android applications, using WebViews. I’ll also be sharing tips on how to improve the user experience, by enhancing the standard WebView component with some of the features you’d expect from a stand-alone web browser.
And, since designing for different screen configurations is always a big part of Android development, we’ll also be looking at ways to ensure the content you’re displaying inside your WebViews looks good and functions correctly across the full range of Android devices.
Build web apps in WebView | Android Developers
Use WebView to deliver a web application
or a web page as a part of a client application. The WebView class is an
extension of Android's View class that lets
you display web pages as a part of your activity layout. It doesn't include the
features of a fully developed web browser, such as navigation controls or an
address bar. All WebView does, by default, is show a web page.
WebView can help you provide information in your app that you might need to
update, such as an end-user agreement or a user guide. Within your Android app,
you can create an Activity that contains a
WebView, then use it to display your document that's hosted online.
WebView can also help when your app provides data to the user that requires an
internet connection to retrieve data, such as email.
In this case, you might
find that it's easier to build a WebView in your Android app that shows a web
page with all the user data, rather than performing a network request, then
parsing the data and rendering it in an Android layout.
Instead, you can design
a web page that's tailored for Android-powered devices and then implement a
WebView in your Android app that loads the web page.
This document describes how to get started with WebView, how to bind
JavaScript from your web page to client-side code in your Android app, how to
handle page navigation, and how to manage windows when using WebView.
Work with WebView on earlier versions of Android
To safely use more-recent WebView capabilities on the device your app is
running on, add the AndroidX
Webkit library. This is a static
library you can add to your application to use android.webkit APIs that aren't
available for earlier platform versions.
Add it to your build.gradle file as follows:
dependencies {
implementation(«androidx.webkit:webkit:1.8.0»)
}
dependencies {
implementation («androidx.webkit:webkit:1.8.0»)
}
Explore the WebView
example on GitHub for more details.
Add a WebView to your app
To add a WebView to your app, you can include the element in your
activity layout or set the entire Activity window as a WebView in
onCreate().
Add a WebView in the activity layout
To add a WebView to your app in the layout, add the following code to your
activity's layout XML file:
To load a web page in the WebView, use
loadUrl(), as
shown in the following example:
val myWebView: WebView = findViewById(R.id.webview)
myWebView.loadUrl(«http://www.example.com»)
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(«http://www.example.com»);
Add a WebView in onCreate()
To add a WebView to your app in an activity's onCreate() method instead, use
logic similar to the following:
val myWebView = WebView(activityContext)
setContentView(myWebView)
WebView myWebView = new WebView(activityContext);
setContentView(myWebView);
Then load the page:
myWebView.loadUrl(«http://www.example.com»)
myWebView.loadUrl(«https://www.example.com»);
Or load the URL from an HTML string:
// Create an unencoded HTML string, then convert the unencoded HTML string into
// bytes. Encode it with base64 and load the data.
val unencodedHtml =
«'%23' is the percent code for ‘#‘ «;
val encodedHtml = Base64.encodeToString(unencodedHtml.toByteArray(), Base64.NO_PADDING)
myWebView.loadData(encodedHtml, «text/html», «base64»)
// Create an unencoded HTML string, then convert the unencoded HTML string into
// bytes. Encode it with base64 and load the data.
String unencodedHtml =
«'%23' is the percent code for ‘#‘ «;
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),
Base64.NO_PADDING);
myWebView.loadData(encodedHtml, «text/html», «base64»);
Note: There are restrictions on what this HTML can do. See
loadData()
and
loadDataWithBaseURL()
for more info about encoding options.
Your app must have access to the internet. To get internet access, request the
INTERNET permission in your
manifest file, as shown in the following example:
…
You can customize your WebView by doing any of the following:
- Enabling fullscreen support using
WebChromeClient. This class
is also called when a WebView needs permission to alter the host app's UI,
such as creating or closing windows or sending JavaScript dialogs to the
user. To learn more about debugging in this context, read Debug web
apps. - Handling events that impact content rendering, such as errors on form
submissions or navigation using
WebViewClient. You can also use
this subclass to intercept URL loading. - Enabling JavaScript by modifying
WebSettings. - Using JavaScript to access Android framework objects that you have injected
into a WebView.
Use JavaScript in WebView
If the web page you want to load in your WebView uses JavaScript, you must
enable JavaScript for your WebView. After you enable JavaScript, you can
create interfaces between your app code and your JavaScript code.
Enable JavaScript
JavaScript is disabled in a WebView by default. You can enable it through the
WebSettings attached to your WebView. Retrieve WebSettings with
getSettings(), then enable
JavaScript with
setJavaScriptEnabled().
See the following example:
val myWebView: WebView = findViewById(R.id.webview)
myWebView.settings.javaScriptEnabled = true
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebSettings provides access to a variety of other settings that you might find
useful.
For example, if you're developing a web application that's designed
specifically for the WebView in your Android app, then you can define a custom
user agent string with
setUserAgentString(),
then query the custom user agent in your web page to verify that the client
requesting your web page is your Android app.
Bind JavaScript code to Android code
When developing a web application that's designed specifically for the WebView
in your Android app, you can create interfaces between your JavaScript code and
client-side Android code. For example, your JavaScript code can call a method in
your Android code to display a Dialog,
instead of using JavaScript's alert() function.
To bind a new interface between your JavaScript and Android code, call
addJavascriptInterface(),
passing it a class instance to bind to your JavaScript and an interface name
that your JavaScript can call to access the class.
Warning: Using addJavascriptInterface() lets JavaScript control your Android
app. Although this can be useful, it can also be a dangerous security issue.
When the HTML in the WebView is untrustworthy—for example, part or all
of the HTML is provided by an unknown person or process—then an attacker
can include HTML that executes your client-side code and possibly any code of
the attacker's choosing. Therefore, don't use addJavascriptInterface() unless
you wrote all of the HTML and JavaScript that appears in your WebView. Don't
let the user navigate within your WebView to web pages that aren't your own.
Instead, let the user's default browser application open foreign links. By
default, the user's web browser opens all URL links, so this warning primarily
applies if you handle page navigation yourself, as described in the following
section.
For example, you can include the following class in your Android app:
/** Instantiate the interface and set the context. */
class WebAppInterface(private val mContext: Context) {
/** Show a toast from the web page. */
@JavascriptInterface
fun showToast(toast: String) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context. */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page. */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
Caution: If you set your
targetSdkVersion to 17 or
later, add the @JavascriptInterface annotation to any method that you want to
be available to your JavaScript. The method must be public. If you don't provide
this annotation, the method isn't accessible by your web page.
In this example, the WebAppInterface class lets the web page create a
Toast message, using the showToast()
method.
You can bind this class to the JavaScript that runs in your WebView with
addJavascriptInterface(), as shown in the following example:
val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), «Android»)
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), «Android»);
This creates an interface called Android for JavaScript running in the
WebView. At this point, your web application has access to the
WebAppInterface class. For example, here's some HTML and JavaScript that
creates a toast message using the new interface when the user taps a button:
There's no need to initialize the Android interface from JavaScript. The
WebView automatically makes it available to your web page. So, when a user
taps the button, the showAndroidToast() function uses the Android interface
to call the WebAppInterface.showToast() method.
Note: The object that is bound to your JavaScript runs in another thread and not
in the thread in which it is constructed.
Handle page navigation
When the user taps a link from a web page in your WebView, by default, Android
launches an app that handles URLs. Usually, the default web browser opens and
loads the destination URL.
However, you can override this behavior for your
WebView so links open within your WebView.
You can then let the user
navigate backward and forward through their web page history that's maintained
by your WebView.
Note: For security reasons, the system's browser app doesn't share its
application data with your app.
To open links tapped by the user, provide a WebViewClient for your WebView
using
setWebViewClient().
All links the user taps load in your WebView. If you want more control over
where a clicked link loads, create your own WebViewClient that overrides the
shouldOverrideUrlLoading()
method. The following example assumes that MyWebViewClient is an inner class
of Activity.
private class MyWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (Uri.parse(url).host == «www.example.com») {
// This is your website, so don't override. Let your WebView load
// the page.
return false
}
// Otherwise, the link isn't for a page on your site, so launch another
// Activity that handles URLs.
Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
startActivity(this)
}
return true
}
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if («www.example.com».equals(request.getUrl().getHost())) {
// This is your website, so don't override. Let your WebView load the
// page.
return false;
}
// Otherwise, the link isn't for a page on your site, so launch another
// Activity that handles URLs.
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
startActivity(intent);
return true;
}
}
Then create an instance of this new WebViewClient for the WebView:
val myWebView: WebView = findViewById(R.id.webview)
myWebView.webViewClient = MyWebViewClient()
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
Now when the user taps a link, the system calls the
shouldOverrideUrlLoading() method, which checks whether the URL host matches
a specific domain, as defined in the preceding example.
If it does match, then
the method returns false and doesn't override the URL loading. It lets the
WebView load the URL as usual.
If the URL host doesn't match, then an
Intent is created to launch the default
Activity for handling URLs, which resolves to the user's default web browser.
Handle custom URLs
WebView applies restrictions when requesting resources and resolving links
that use a custom URL scheme. For example, if you implement callbacks such as
shouldOverrideUrlLoading()
or
shouldInterceptRequest(),
then WebView invokes them only for valid URLs.
WebView
Загружаем локальные страницы и картинки Загружаем данные при помощи loadData() и loadDataWithBaseURL() Проблемы с кодировкой Методы Используем зум для просмотра Прозрачность Настройки Ночной режим
WebView — это компонент, который позволяет встраивать веб-страницы в приложения, своеобразный мини-браузер. Находится в разделе Containers.
В старых версиях Android WebView использовал движок WebKit. В Android 4.4 он стал использовать движок Chromium или Blink. В Android 5 появилось отдельное приложение System WebView, которое можно скачать из Play Market. Такое разделение позволило обновлять движок без обновления системы.
На этом приключения не закончились. В Android 7.0 уже используется движок Chrome, а если этого браузера на устройстве нет, то используется System WebView. Подобные выкрутасы не прошли даром, программисты часто жалуются, что какой-то кусок кода не работает. Приходится проверять работу на разных устройствах.
Надеюсь, вы уже познакомились с базовым примером по созданию собственного браузера. Рассмотрим дополнительные возможности элемента WebView.
Загружаем локальные страницы и картинки
Если вы хотите загружать в WebView страницы не из интернета, а со своего приложения, то разместите нужные файлы в папке assets, например, assets/mypage.html. Доступ к файлу вы можете получить через конструкцию file://android_asset:
webView = findViewById(R.id.mybrowser);
webView.loadUrl(«file:///android_asset/mypage.html»);
Аналогично поступаем с картинками, которые встречаются в html-файле
Также можно загрузить файл из папки res/raw:
webView.loadUrl(«file:///android_res/raw/cat.html»);
Если картинка находится на внешнем накопителе, то попробуйте вариант:
WebView webView = findViewById(R.id.webView);
String imageName = «cutecat.png»;
String catUrl = «file://»
+ Environment.getExternalStorageDirectory().getAbsolutePath()
.toString() + «/» + imageName;
webView.loadUrl(catUrl);
Недавно наткнулся на фрагмент кода, где нужно добавить несколько новых настроек для работы с файлами. Пример для Kotlin.
val webView = findViewById(R.id.webView)
// Enable the WebView to access content through file: URLs
webView.settings.apply {
allowFileAccess = true
allowFileAccessFromFileURLs = true
allowUniversalAccessFromFileURLs = true
}
Загружаем данные при помощи loadData() и loadDataWithBaseURL()
Данные можно загрузить с помощью метода loadData():
String htmlText = «Percent test: 100% «;
WebView webView = findViewById(R.id.webView);
webView.loadData(htmlText, «text/html», «en_US»);
Если текст простой, то этот способ подойдёт. Но в данном примере встречается символ процента, который относится к спецсимволам и часть текста может оказаться недоступной. Если в тексте встречаются подобные символы, то лучше использовать метод loadDataWithBaseURL():
webView.loadDataWithBaseURL(null, htmlText, «text/html», «en_US», null);
Если вам приходится использовать loadData(), то спецсимволы можно заменить при помощи метода replace():
String webData = stringBuffer.toString(); // поступающие данные
webData = webData.replace(«#», «%23»);
webData = webData.replace(«%», «%25»);
webData = webData.replace(«\», «%27»);
webData = webData.replace(«?», «%3f»);
webView.loadData(webData, «text/html», «UTF-8»);
Проблемы с кодировкой
Working with the WebView
If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout. Since Android 4.4, it is based on the Chrome on Android v33.0.0 according to this reference.
This document shows you how to get started with WebView and how to do some additional things, such as handle page navigation and bind JavaScript from your web page to client-side code in your Android application. See the official WebView docs for a more detailed look.
An alternative for using WebViews is Chrome Custom Tabs, which provides more flexibility in terms of customizing the toolbar, adding animations, or warming up the browser ahead of time. Chrome Custom Tabs only works if Chrome on Android is installed on the browser. For more information, see this guide.
Usage
Load External Pages
To get Internet access, request the INTERNET permission in your manifest file. For example:
…
To add a WebView to your Application, simply include the element in your activity layout:
First, we need to configure the WebView to behave with reasonable defaults using WebSettings and creating a WebViewClient:
public class MainActivity extends Activity { private WebView myWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myWebView = (WebView) findViewById(R.id.webview); // Configure related browser settings myWebView.getSettings().setLoadsImagesAutomatically(true); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // Configure the client to use when opening URLs myWebView.setWebViewClient(new WebViewClient()); // Load the initial URL myWebView.loadUrl(«https://www.example.com»);
}
}
class MainActivity : Activity() { private lateinit var myWebView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val myWebView = findViewById(R.id.webview) as WebView myWebView.apply { // Configure related browser settings this.settings.loadsImagesAutomatically = true this.settings.javaScriptEnabled = true myWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY // Configure the client to use when opening URLs myWebView.webViewClient = WebViewClient() // Load the initial URL myWebView.loadUrl(«https://www.example.com»)
}
}
}
You can attach javascript functions and use them within the mobile webpages as described here in the official docs.
Handling responsive layouts
By default, the WebView does not account for the default scale size if HTML pages include viewport metadata. If you wish to enable the page to load with responsive layouts, you need to set it explicitly:
// Enable responsive layout
myWebView.getSettings().setUseWideViewPort(true);
// Zoom out if the content width is greater than the width of the viewport
myWebView.getSettings().setLoadWithOverviewMode(true);
// Enable responsive layout
myWebView.getSettings().setUseWideViewPort(true)
// Zoom out if the content width is greater than the width of the viewport
myWebView.getSettings().setLoadWithOverviewMode(true)
You can also enable the ability to zoom-in controls on the page:
myWebView.getSettings().setSupportZoom(true);
myWebView.getSettings().setBuiltInZoomControls(true); // allow pinch to zooom
myWebView.getSettings().setDisplayZoomControls(false); // disable the default zoom controls on the page
myWebView.getSettings().setSupportZoom(true)
myWebView.getSettings().setBuiltInZoomControls(true) // allow pinch to zooom
myWebView.getSettings().setDisplayZoomControls(false) // disable the default zoom controls on the page
Loading Local Pages
In case you want to store a copy of a webpage locally to be loaded into a WebView, you can put it in the android assets folder. If you do not find one under your main/ directory, then you can create one. Place the html, css, js, etc in this folder.
For example, say I wanted to load a page entitled index.html. I would create my file under {ProjectName}/app/src/main/assets/index.html
then, in your activity or fragment you can use the code
public class MainActivity extends Activity { private WebView myWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myWebView = (WebView) findViewById(R.id.webview); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient()); String path = Uri.parse(«file:///android_asset/index.html»).toString(); myWebView.loadUrl(path);
}
}
class MainActivity : Activity() { private lateinit var myWebView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val myWebView = findViewById(R.id.webview) as WebView myWebView.apply { // Configure related browser settings this.settings.loadsImagesAutomatically = true this.settings.javaScriptEnabled = true myWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY // Configure the client to use when opening URLs myWebView.webViewClient = WebViewClient() // Load the initial URL myWebView.loadUrl(«https://www.example.com») val path: String = Uri.parse(«file:///android_asset/index.html»).toString()
myWebView.loadUrl(path)
}
}
}
Displaying a ProgressDialog in a WebView
Create your ProgressDialog in the setWebViewClient method
You can dismiss the dialog in onPageFinished method or in onPageCommitVisible. Setting dismis in the latter is convenient since your user won't have to wait for the whole page to load to proceed.
webView.setWebViewClient(new WebViewClient() { ProgressDialog progressDialog = new ProgressDialog(Context); @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); progressDialog.setTitle(«Loading…»); progressDialog.setMessage(«Please wait…»); progressDialog.setCancelable(false); progressDialog.show(); } @Override public void onPageCommitVisible(WebView view, String url) { super.onPageCommitVisible(view, url); if (progressDialog != null){ progressDialog.dismiss();
}
}
});
webView.setWebViewClient(object : WebViewClient() { val progressDialog: ProgressDialog? = ProgressDialog(Context) override fun onPageStarted( view: WebView, url: String, favicon: Bitmap ) { super.onPageStarted(view, url, favicon) progressDialog.setTitle(«Loading…») progressDialog.setMessage(«Please wait…») progressDialog.setCancelable(false) progressDialog.show() } override fun onPageCommitVisible( view: WebView, url: String ) { super.onPageCommitVisible(view, url) if (progressDialog != null) {
progressDialog.dismiss()
}
}
})
Sharing cookies between WebViews and networking clients
WebViews currently use their own cookie manager, which means that any network requests you make outside of these web views are usually stored separately. This can cause problems when trying to retain the same cookies (i.e.
for authentication or cross-site script forgery (CSRF) headers). The simplest approach as proposed in this Stack Overflow article is to implement a cookie handler that forwards all requests to the WebView cookie store.
See this gist for an example.
References
Работа с сетью. WebView
Последнее обновление: 17.10.2021
WebView представляет простейший элемент для рендеринга html-кода, базирующийся на движке WebKit.
Благодаря этому мы можем использовать WebView как примитивный веб-браузер, просматривая через него контент из сети интернет.
Использование движка WebKit гарантирует, что отображение контента будет происходить примерно такжe, как и в других браузерах, построенных на этом движке — Google Chrome и Safari.
Некоторые основные методы класса WebView:
- boolean canGoBack(): возвращает true, если перед текущей веб-страницей в истории навигации WebView еще есть страницы
- boolean canGoForward(): возвращает true, если после текущей веб-страницей в истории навигации WebView еще есть страницы
- void clearCache(boolean includeDiskFiles): очищает кэш WebView
- void clearFormData(): очищает данный автозаполнения полей форм
- void clearHistory(): очищает историю навигации WebView
- String getUrl(): возвращает адрес текущей веб-страницы
- void goBack(): переходит к предыдущей веб-странице в истории навигации
- void goForward(): переходит к следующей веб-странице в истории навигации
- void loadData(String data, String mimeType, String encoding): загружает в веб-браузере данные в виде html-кода, используя указанный mime-тип и кодировку
- void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl): также загружает в веб-браузере данные в виде html-кода, используя указанный mime-тип и кодировку, как и метод loadData(). Однако кроме того, в качестве первого параметра принимает валидный адрес, с которым ассоциируется загруженные данные. Зачем нужен этот метод, если есть loadData()? Содержимое, загружаемое методом loadData(), в качестве значения для window.origin будет иметь значение null, и таким образом, источник загружаемого содержимого не сможет пройти проверку на достоверность. Метод loadDataWithBaseURL() с валидными адресами (протокол может быть и HTTP, и HTTPS) позволяет установить источник содержимого.
- void loadUrl(String url): загружает веб-страницу по определенному адресу
- void postUrl(String url, byte[] postData): отправляет данные с помощью запроса типа «POST» по определенному адресу
- void zoomBy(float zoomFactor): изменяет масштаб на опредленный коэффициент
- boolean zoomIn(): увеличивает масштаб
- boolean zoomOut(): уменьшает масштаб
Работать с WebView очень просто. Определим данный элемент в разметке layout:
Для получения доступа к интернету из приложения, необходимо указать в файле манифеста AndroidManifest.xml соответствующее разрешение:
Чтобы загрузить определенную страницу в WebView, через метод loadUrl() надо установить ее адрес:
package com.example.viewapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser=findViewById(R.id.webBrowser);
browser.loadUrl(«https://metanit.com»);
}
}
Вместо определения элемента в layout мы можем создать WebView в коде Activity:
WebView browser = new WebView(this);
setContentView(browser);
browser.loadUrl(«http://metanit.com»);
Кроме загрузки конкретной страницы из интернета с помощью метод loadData():
WebView browser= findViewById(R.id.webBrowser);
browser.loadData(»
Hello, Android!
«, «text/html», «UTF-8»);
Первым параметром метод принимает строку кода html, во втором — тип содержимого, а в третьем — кодировку.
JavaScript
По умолчанию в WebView отключен javascript, чтобы его включить надо применить метод setJavaScriptEnabled(true) объекта WebSettings: