Enabling javascript android webview

Взаимодействие WebView с JavaScript

WebView — это компонент, с помощью которого можно отображать веб-страницы. Однако нас интересует не только показ содержимого страницы, нам нужно также взаимодействовать с этим содержимым. В этой статье мы попытаемся объяснить некоторые детали этого процесса.

Важно! Прежде всего, если вы хотите загрузить веб-страницу из Интернета, не забудьте добавить следующее разрешение в файл AndroidManifest.xml.

Есть несколько способов задать содержимое для WebView.

Класс WebSettings

Этот класс позволяет управлять настройками состояния WebView. Когда WebView создаётся, он получает набор настроек по умолчанию. Эти настройки по умолчанию можно получить с помощью вызова геттера. Объект WebSettings, полученный из webView.getSettings(), привязан к времени существования этого объекта WebView. Если WebView был уничтожен, любой вызов метода WebSettings вызовет исключение IllegalStateException.

Чтобы использовать JavaScript, нужно включить его, вызвав у объекта WebSettings метод setJavaScriptEnabled().

Класс WebViewClient

WebViewClient вызывается, когда выполняется рендеринг содержимого страницы. Вы также можете перехватит здесь загрузку URL (с помощью метода shouldOverrideUrlLoading()).

WebViewClient позволяет прослушивать события веб-страницы, например, когда она начинает загружаться, или завершила загрузку, когда произошла ошибка, связанная с загрузкой страницы, отправкой формы, ссылками, и другими событиями.

Реализация экземпляра WebViewClient может быть, например, следующей.

Затем задать WebViewClient для WebView можно с помощью метода setWebViewClient().

Класс WebChromeClient

Этот класс позволяет прослушивать вызовы JavaScript, уведомления текущей страницы, такие как сообщения консоли, предупреждения, прогресс обновления страницы и другие вызовы JavaScript.

С помощью WebChromeClient мы можем обрабатывать события JS.

Затем задать экземпляр WebChromeClient можно следующим способом.

Привязка JavaScript к Android

WebView позволяет привязать код JavaScript к коду Android через интерфейс.

Для этого мы должны использовать метод addJavaScriptInterface(), в который передаются класс, предоставляющий интерфейс для JS, и имя, которое будет использоваться для отображения экземпляра в JS (например, «AndroidFunction«). В результате будет создан интерфейс с именем AndroidFuction для JavaScript, работающего в WebView.

С помощью этого способа мы можем:

  1. Выполнить метод, описанный в Java, из JS.
  2. Выполнить из Java метод, описанный в JS.

JavaScript вызывает Java

Например, опишем класс с нашими методами, которые мы хотим выполнить в JS.

Примечание: аннотация @JavascriptInterface обязательна для API 17 и выше.

Затем установим этот интерфейс в WebView.

Для взаимодействия с java-кодом в JS мы должны использовать имя интерфейса.

Java вызывает JavaScript

Допустим, у нас есть такой код на HTML.

Тогда в Java-коде нам нужно добавить вызов метода loadUrl(), в параметры которого нужно передать имя объявленного в JS метода.

После этого, загрузив страницу, мы можем выполнять код JavaScript прямо из Java.

Взаимодействие WebView с JavaScript : 7 комментариев

Спасибо большое! Гениальная статья 😉

Так а все таки если из Java надо запустить JS функцию это надо постоянно перезапускать вебвью через loadurl по сути?

«После этого, загрузив страницу, мы можем выполнять код JavaScript прямо из Java.»

так вот это вот как.

а понял. вызов не очищает вебвью. только медленно оно ((

Все получилось, спасибо! Долго не мог найти ответа

Источник

Работа с сетью. WebView

WebView

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() надо установить ее адрес:

Вместо определения элемента в layout мы можем создать WebView в коде Activity:

Кроме загрузки конкретной страницы из интернета с помощью метод loadData() :

Первым параметром метод принимает строку кода html, во втором — тип содержимого, а в третьем — кодировку.

JavaScript

По умолчанию в WebView отключен javascript, чтобы его включить надо применить метод setJavaScriptEnabled(true) объекта WebSettings:

Источник

Getting Started: WebView-based Applications for Web Developers

Published on Friday, February 28, 2014

Getting started with the Android WebView is fairly simple, whether you want load a remote URL or display pages stored in your app.

This tutorial walks you through creating a new Android Project, adding a WebView, loading a remote URL, and then loading a local HTML page.

Note: This tutorial assumes you’re a developer with limited or no experience with the Android development environment, but have some experience with Java. If you’re already familiar with programming for Android, you may want to refer to to Building Web Apps in WebView on the Android developer site instead.

# Install Android Studio

This tutorial uses Android Studio, the new design-and-build IDE for Android. So you’ll need start off by installing Android Studio, as described here:

# Create a New Android Project

When the installation completes, Android Studio launches and displays the welcome screen.

To create a new project:

Click New Project.

On the next page, enter your application name, package name and target SDKs, and click Next.

Note: If you only intend to support the Chromium WebView (rather than the old WebKit WebView) set Minimum required SDK to API 19: Android 4.4 (KitKat).

On the next page, you’re prompted to enter an application icon. (You can change the icon later, so don’t worry if you don’t have one right now.) When you’re done, click Next.

The next page lets you select the main Android activity for your application. For the purposes of this guide, select Blank Activity and click Next.

Note: An Android Activity can be viewed as a screen of an app. In this case, the application’s main activity will hold the web view. If you’re planning to venture further into native Android development, you can find more information in the Android Activities API guide

The next page lets you change the names for the default Activity and layout. Click Finish to accept the defaults and create the project.

You now have a new Android project. Next, to add the WebView!

Note: After you have your project created, make sure you have the KitKat SDK installed. Go to Tools > Android > SDK Manager and make sure you have Android 4.4 (API 19) installed.

# Add the WebView

Android Studio will give you some boilerplate code to set up your application. Your project’s structure should look something like this:

A few of the more import folders are identified in the picture:

  1. src/main/java . Android Java source code.
  2. src/main/res . Resources used by the native application.
  3. src/main/res/drawable-_type_ . Image resources used by the native application.
  4. src/main/res/layout . XML layout files that define the structure of UI components.
  5. src/main/res/values . Dimensions, strings, and other values that you might not want to hard-code in your application.
  6. src/main/AndroidManifest.xml . The manifest file defines what’s included in the application: activities, permissions, themes, and so on.
Читайте также:  Форматы читалок для андроид

You need to add a WebView to the main activity’s layout.

Open the activity_main.xml file in the src/main/res/layout directory if it is not already open. (You may also see a fragment_main.xml file. You can ignore this, as it’s not required for this tutorial.)

Select the Text tab at the bottom of the of the activity_main.xml editor to see the XML markup.

This file defines the layout for your main activity, and the Preview panes show the a preview of the activity. The Blank Activity layout doesn’t include any children. You’ll need to add the WebView.

In the XML pane, remove the self-closing slash from the end of the FrameLayout element, and add the element and a new closing tag, as shown:

To use the WebView you need to reference it in the Activity. Open the Java source file for the main activity, MainActivity.java in the src/main/java/

Add the lines shown in bold.

The existing code in the onCreate method does the work of hooking up the Activity with the layout. The added lines create a new member variable, mWebView , to refer to the web view.

Remove the following code:

The WebView is identified by the resource ID, which is specified by this line in the layout file:

After adding the code, you’ll see some warning messages in the margin of the editor. This is because you haven’t imported the right classes for WebView. Luckily Android Studio can help you fill in the missing classes. The easiest way to do this is click and hover over an unknown class name and wait for a popup showing a «quick fix» — in this case, adding an import statment for the WebView class.

Press Alt + Enter (Option + Enter on Mac) to accept the quick fix.

WebView in hand you can move on to setting it up and and loading some juicy web content.

# Enable JavaScript

WebViews don’t allow JavaScript by default. To run a web application in the web view, you need to explicitly enable JavaScript by adding the following lines to the onCreate method:

# Load a Remote URL

If you’re going to load data from a remote URL, your application needs permission to access the internet. This permission needs to be added in the application’s manifest file.

Open the AndroidManifest.xml file in the src/res directory. Add the line in bold before the closing tag.

The next step is to call the loadUrl method on the webview. Add the following line to the end of the onCreate method.

Now try running the project. If you don’t have a device handy, you can create an emulator (AVD or Android Virtual Device) by going to Tools > Android > AVD Manager.

Note: To detect when a URL has started and finished loading, use WebViewClient.onPageStarted and WebViewClient.onPageFinished .

# Handling Navigation

Now try changing the URL you’re loading to http://www.html5rocks.com/ and rerun your application. You’ll notice something strange.

If you run the application now with a site that has a redirect like html5rocks.com , your app ends up opening the site in a browser on the device, not in your WebView — probably not what you expected. This is because of the way the WebView handles navigation events.

Here’s the sequence of events:

  1. The WebView tries to load the original URL from the remote server, and gets a redirect to a new URL.
  2. The WebView checks if the system can handle a view intent for the URL, if so the system handles the URL navigation, otherwise the WebView will navigate internally (i.e. the user has no browser installed on their device).
  3. The system picks the user’s preferred application for handling an http:// URL scheme — that is, the user’s default browser. If you have more than one browser installed, you may see a dialog at this point.

If you’re using a WebView inside an Android application to display some simple web content (for example, a help page), this may be exactly what you want to do. However, for more sophisticated applications, you may want to handle the navigation links yourself.

Читайте также:  Мобильный клиент pokerstars для android

To handle navigation inside the WebView you need to override the WebView’s WebViewClient , which handles various events generated by the WebView. You can use it to control how the WebView handles link clicks and page redirects.

The default implementation of WebViewClient makes any URL open in the WebView:

This is a good step forward, but what if you want to handle links for your site only, while opening other URLs in a browser?

To achieve this you need to extend the WebViewClient class and implement the shouldOverrideUrlLoading method. This method is called whenever the WebView tries to navigate to a different URL. If it returns false, the WebView opens the URL itself. (The default implementation always returns false, which is why it works in the previous example.)

Create a new class:

Right-click the package name of your app and select New > Java Class

Enter MyAppWebViewClient as the class name and click OK

In the new MyAppWebViewClient.java file, add the following code (changes shown in bold):

The new code defines MyAppWebViewClient as a subclass of WebViewClient and implements the shouldOverrideUrlLoading method.

The shouldOverrideUrlLoading method is called whenever the WebView is about to load a URL. This implementation checks for the String «html5rocks.com» at the end of the host name of the URL. If the string exists, the method returns false, which tells the platform not to override the URL, but to load it in the WebView.

For any other hostname, the method makes a request to the system to open the URL. It does this by creating a new Android Intent and using it to launch a new activity. Returning true at the end of the method prevents the URL from being loaded into the WebView.

To use your new custom WebViewClient, add the following lines to your MainActivity class:

Now, a user can click any of the HTML5Rocks links and stay within the app, but links to external sites are opened in a browser.

# Handling the Android Back Button

As you start playing around and navigating the awesome HTML5Rocks articles, hitting the back button on Android exits the application, even though you’ve explored a few pages of the site.

WebView has a method canGoBack which tells you if there is anything on the page stack that can be popped. All you need to do is detect a back button press and determine if you should step back through the WebView’s history or allow the platform to determine the correct behaviour. Inside your MainActivity class, add the following method (in bold):

# Loading HTML files from the file system

A big advantage of using a WebView inside an installable application is that you can store assets inside the app. This lets your app work offline and improves load times, since the WebView can retrieve assets directly from the local file system.

To store files such as HTML, JavaScript, and CSS locally, put them in the assets directory. This is a reserved directory that Android uses for raw files that your app may need access to (i.e. files it knows it should minimise or compress).

In your project, create the assets directory in main ( src/main/assets ).

Generally it’s good practice to keep your web files in a subdirectory, so create a www directory and put all your web content in it.

Note: Absolute paths do not work in the WebView when referring to other files, such as CSS and JavaScript. So make sure you make all references relative, instead of absolute (for example, instead of «/pages/somelink.html», use «./pages/somelink.html»).

Once you have everything in your assets directory, it’s as simple as loading in the appropriate file:

You’ll want to tweak the shouldOverrideUrlLoading method so it opens a browser for non-local pages:

Now you are set to build a great WebView app!

For tips on getting the visuals just right, see Pixel-Perfect UI in the WebView.

If you run into trouble, the Chrome DevTools are your friends. See Remote Debugging on Android to get started.

Last updated: Friday, February 28, 2014 • Improve article

Источник

Оцените статью