Webview android javascript error

I'm trying to run javascript in WebView in an app. I'm developing on Nexus 7. The html / javascript works fine on Chromium, but certain actions aren't happening on the tablet. Is there a way of se...

I’m trying to run javascript in WebView in an app. I’m developing on Nexus 7.

The html / javascript works fine on Chromium, but certain actions aren’t happening on the tablet. Is there a way of seeing if any of the javascript itself is failing on the tablet? A kind of console view?

asked Feb 13, 2013 at 18:00

interstar's user avatar

interstarinterstar

25.4k36 gold badges110 silver badges177 bronze badges

You can actually receive the console messages from a WebView, which would allow you to catch the errors that it throws.

To do so:

  1. Enable JavaScript on your WebView
  2. Set a WebChromeClient
  3. Override onConsoleMessage

Example:

    final WebView webView = (WebView) findViewById(R.id.webview_terms_conditions);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d("MyApplication", consoleMessage.message() + " -- From line "
                    + consoleMessage.lineNumber() + " of "
                    + consoleMessage.sourceId());
            return super.onConsoleMessage(consoleMessage);
        }
    });

    webView.loadUrl(getString(R.string.url_terms_conditions));

Similar to what it says here, though that doc isn’t complete and it uses a deprecated method.


When running on Android KitKat, you can also enable remote debugging!

answered Nov 8, 2016 at 11:02

RominaV's user avatar

4

You can use Remote Debugging WebViews

Chrome Devtools Remote Debugging

More info

Debug WebViews in your native Android apps using Chrome Developer Tools.

On Android 4.4 (KitKat) or later, use DevTools to debug WebView content in native Android applications.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    WebView.setWebContentsDebuggingEnabled(true);
}

Type chrome://inspect in pc browser
enter image description here

answered Sep 24, 2018 at 4:56

Ahmad Aghazadeh's user avatar

Ahmad AghazadehAhmad Aghazadeh

16.4k11 gold badges101 silver badges97 bronze badges

3

Community's user avatar

answered Feb 13, 2013 at 18:03

sachleen's user avatar

sachleensachleen

30.4k8 gold badges77 silver badges73 bronze badges

1

In Android Studio «Arctic Fox» just look in logcat. Message with «cromium» tag.

answered Dec 2, 2021 at 12:33

Falchio's user avatar

Post Views: 35 368

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

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

<uses-permission android:name="android.permission.INTERNET"/>

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

WebView webView = findViewById(R.id.WebView);
// Пример 1: задать URL адрес
webView.loadUrl("https://android-tools.ru");
// Пример 2: задать HTML-файл из папки raw
webView.loadUrl("file:///Android_res/raw/some_file.HTML");
// Пример 3: задать HTML-файл из папки assets
webView.loadUrl("file:///Android_asset/some_file.HTML");
// Пример 4: задать содержимое HTML в виде строки
String rawHTML = "<HTML>"+ "<body><h1>HTML content</h1></body>"+ "</HTML>";
webView.loadData(rawHTML, "text/HTML", "UTF-8");

Класс WebSettings

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

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

WebView webView = findViewById(R.id.WebView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

Класс WebViewClient

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

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

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

private class MyWebViewClient extends WebViewClient {
  @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    return super.shouldOverrideUrlLoading(view, request);
  }

  @Override public void onPageFinished(WebView view, String url) {
  }

  @Override
  public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
    super.onReceivedError(view, request, error);
  }
}

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

webView.setWebViewClient(new MyWebViewClient());

Класс WebChromeClient

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

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

private class MyWebChromeClient extends WebChromeClient {
  @Override
  public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
    return true;
  }

  @Override
  public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
    return true;
  }

  @Override
  public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
      final JsPromptResult result) {
    return true;
  }
}

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

webView.setWebChromeClient(new MyWebChromeClient());

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

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

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

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

JavaScript вызывает Java

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

public class JavaScriptInterface {
  Context mContext;

  JavaScriptInterface(Context c) {
    mContext = c;
  }

  @JavascriptInterface
  public void showToast(String toast) {
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
  }
}

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

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

webView.addJavascriptInterface(new JavaScriptInterface(this), "AndroidFunction");

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

<!DOCTYPE >
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
           function init()
           {
              var testVal = 'Привет от Android Tools!';
              AndroidFunction.showToast(testVal);
           }
        </script>
  </head>
  <body>
    <div style="clear: both;height: 3px;"> </div>
    <div>
      <input value="submit" type="button" name="submit"
           id="btnSubmit" onclick="javascript:return init();" />
    </div>
  </body>
</html>

Java вызывает JavaScript

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

<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <center><b><u>Javascript</u></b></center>
    <div id="msg">0</div>
    <script>
      function increment() {
      var ob = document.getElementById("msg");
      ob.innerText = parseInt(ob.innerText) + 1;
      }
    </script>
  </body>
</html>

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

webView.loadUrl("javascript:increment()");

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

andrisole92 opened this issue

Jun 27, 2017

· 48 comments

Comments

@andrisole92

Description

When I open WebView on Android emulator or real device it does not execute JavaScript. I have run simple Android App in Android Studio and it worked there.

Reproduction Steps

Just create a new app and add this WebView to it

Sample Code

<WebView
                style={[styles.flex]} //styles
                javaScriptEnabled={true} //enabling JavaScript
                source={{uri: 'http://partners.zeew.eu/'}} //Url
            />

Solution

Can you please check it and say what is wrong?

Additional Information

  • React Native version: 0.45.1
  • Platform: Android ( not sure about iOS )
  • Development Operating System: Windows
  • Build tools: Android Studio: Nexus 5x edited_api_25 Android 6.0 Google APIs, Nexus 5 API level 26, Android 8.0.0

@hramos

Can you reproduce this using Snack?

@andrisole92

Yes: https://snack.expo.io/H18CZMeVW
You may want to check WebView URL in the browser and see when the button in clicked it goes interactive: http://partners.zeew.eu/

But in WebView, when I click a button nothing happens. Same thing with my second website, where the entire page does not load, because it is all in JavaScript.

@hramos

Any chance you can write a minimal reproduction? Such as loading a very simple website with minimal JavaScript, as opposed to your actual app.

@andrisole92

I am using React-navigation (https://reactnavigation.org/), that’s why I can’t reproduce it fully.
There are two buttons in my app: Login and Register.
When I click on Register, there is a function, that navigates me to the Screen with the WebView, identical to one that I have posted above on Snack.

@andrisole92

Anyway, a simple page with only a WebView should be displaying JavaScript with javaScriptEnabled option, right? And it is not.

@UtenteBello

I have added a html template into react native webView, but when i run the app on IPad don’t work the css files linked on html template.

@UtenteBello

@andrisole92

Can you show me your code?

@UtenteBello

import React, { Component } from ‘react’;
import {
AppRegistry,
StyleSheet,
Text,
View,
WebView,
} from ‘react-native’;

export default class Products extends Component {
render() {
return (
<WebView
source={require(‘./Prova.html’)}
/>
);
}
}

AppRegistry.registerComponent(‘Products’, () => Products);

@UtenteBello

This is my index.ios, and Prova.html is a simple file liked to css file

@pankaj-ag

I am having the same issue.

@andrisole92

That is why I stopped using React-Native tbh

@andrisole92

The community does not seem to be really strong and supportive.

concernedrat, tg-tradelab, HanggiAnggono, MahbbRah, AdamZaczek, blyszcz, tshradheya, tobzy, MSturges, GMButters, and 16 more reacted with thumbs up emoji
andyesp, karanpratapsingh, guguji5, helal-khan, kevinNejad, saul-mtz, scorpionknifes, igor-shyrnin, and anupammaurya reacted with thumbs down emoji
Manntravel, krishan1kamal, tshradheya, devilsbibble, and elmahyai reacted with laugh emoji
karanpratapsingh, btk, helal-khan, tshradheya, samerdernaika, GMButters, scorpionknifes, elmahyai, and igor-shyrnin reacted with confused emoji
rafarx reacted with rocket emoji
nikilmethew, bephrem1, and bohehe reacted with eyes emoji

@charpeni

@koenpunt

For me the page loaded in the webview has no problem using JavaScript, but the injected JavaScript doesn’t get executed without javaScriptEnabled set to true

@pankaj-ag

somehow its not working in android emulator but its working fine in my device.

@ishita-kothari

I am trying to attach html file in webview. the html file contains css and js files as in regular webpages. I am trying to open webView after navigation. Code for WebView is:

const html = require( ‘../path/index.html’)

               <WebView source={html}
                                 style={{height: 700}}
                        />

With this code I am unable to run js on my app. I have also tried javaScriptEnabled to true, but no luck. Also when I build app, it shows me blank page instead of html content.

please help me resolve conflict.

@pankaj-ag

@ishita-kothari

@pankaj-ag I have tried all the possible ways.

I have local html file placed in android/app/src/main/assets/folder/index/html. This html has injected js in it. I am unable to load js. the js file contains my data. app works fine when I add source url of live site, but with local file it doesnot load properly. my data is not loaded. Please provide me solution.

@pankaj-ag

@ishita-kothari can you provide the code snippet here of your web view implementation.
I was also having the same problem in my emulator. So can you test your code on actual devices?

@ishita-kothari

<!-- google fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600,700i|PT+Serif:400,400i,700" rel="stylesheet">
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/styles.css?v2.1">

<style type=»text/css»>
.languages{
text-align: center;
list-style: none;
font-size: 1.1em;
padding-top: 1em;
}
.languages li{
display: inline-block;
padding: 0 1em;
text-decoration: underline;
}
.languages a:hover{
opacity: 0.8;
cursor: pointer;
}
.languages a.selected{
color: #cd6b6d;
font-weight: bold;
}
</style>

<div class = "story">
   <div id = "search-container" >
       <input type="text" id="search" placeholder="Start typing to search for an item" autocomplete="off"></input>
       </div>
  <div class="copy-container">
     
      <div class="results">
          <div class="no-results">No results found</div>
      </div>
  </div>

</div>
<script type="text/javascript" src = "./js/bundle.js?v3.3"></script>

this is the html file. bundle.js file contains the data.

@ishita-kothari

can anyone tell me how to include <script> tag in webview?

@cgathergood

Any updates to this issue? I’ve ran into a similar issue with inline JS — thanks!

@AbdallaElabd

Same here. Even after putting the Javascript directly in the html, it’s still not being executed on Android.

@dlikhachev

Any updates on this? I’m facing the same problem now.

@a-r-d

Hey I’m also having a similar problem. Some of the javascript in my Android webview will fail to execute, but there seems to be no way to get debug information or error messages. Does anyone know how to read the console on the embedded webview? I have resorted to doing stuff like this:

<div id="hello"></div>
<script>
document.getElementById('hello').textContent = "Hello World....";
</script>

Which obviously does not always work because sometimes javascript fails to execute in the webview and I cannot see the console output.

@Jahans3

@a-r-d I’ve done something similar sending a value from a Swift JSContext back into the native layer, it should work the same (in principle) when posting between different JS environment.

I haven’t tried running this code but it shouldn’t take much to get it to work. The idea is to override console.log so that it instead posts a message back into the RN layer.

injectedJavaScript:

(function () {
  var originalConsoleLog = console.log || window.console.log;
  var patchedConsoleLog = function (message) {
    originalConsoleLog && originalConsoleLog(message);
    window.postMessage && window.postMessage(message);
  };
  console.log = patchedConsoleLog;
})();

handler:

_onMessage = message => {
  console.log(message);
}

WebView:

<WebView onMessage={this._onMessage} />

You may always wish to add an identifier to the patchedConsoleLog so that you can filter messages intended for logging :)

@ggsrivas

Javascript execution in webview is not working for android API version 21 and below. Anyone found any solution?

@esutton

@pankaj-ag Thank you!

Why does an emulator WebView not work when same emulator’s native browser does work?

Try running on a real Android device.

  • On an x86 Android emulator, I can NOT get a WebView to run an external URL that
    returns a webpack ( Angular ) bundle ( Other web pages work fine )
  • The same URL works fine if copied to the x86 Android emulator’s native web browser.
  • The same URL works fine running on a WebView on a real Android Device.
  • Other URLs with embedded JS run fine in WebView on emulator.

I am not sure if anything more than javaScriptEnabled is needed.

      render() {
        return (
          <WebView
            source={{ uri: this.props.uri }}
            style={{ marginTop: 0 }}
            scalesPageToFit
            javaScriptEnabled
            domStorageEnabled
            startInLoadingState
            mixedContentMode="always"
          />
        );
      }

@BSN4

Confirmed not working on android emulator but works with real device …

solution : ignore your emulator 💯

@stale

Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community’s attention? This issue may be closed if no further activity occurs. You may also label this issue as «For Discussion» or «Good first issue» and I will leave it open. Thank you for your contributions.

@stale
stale
bot

added
the

Stale

There has been a lack of activity on this issue and it may be closed soon.

label

Jul 5, 2018

@seymoe

@stale
stale
bot

removed
the

Stale

There has been a lack of activity on this issue and it may be closed soon.

label

Jul 28, 2018

@ggsrivas

In my case, it was a code error. I was using a few es6 syntaxes which were not working on webview in lower android versions (my bad). Luckily I could debug webview javascript in android Lollipop (and above) and that where I found this issue.
Javascript execution in webview has been working fine.

@seymoe

@ggsrivas thx! I have tried and find this problem, too. I used let.. hah

@jamonholmgren

@priyankahipoint

To enable javascript popups in WebView its necessary to set webChromeClient and override openFileChooser methods.

    mWebview.setWebChromeClient(new WebChromeClient(){
        // For Android 4.1+
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);

            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(acceptType);

            startActivityForResult(Intent.createChooser(i, "SELECT"), 100);
        }

        // For Android 5.0+
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadMessageArr != null) {
                mUploadMessageArr.onReceiveValue(null);
                mUploadMessageArr = null;
            }

            mUploadMessageArr = filePathCallback;

            Intent intent = fileChooserParams.createIntent();

            try {
                startActivityForResult(intent, 101);
            } catch (ActivityNotFoundException e) {
                mUploadMessageArr = null;

                Toast.makeText(activity,"Some error occurred.", Toast.LENGTH_LONG).show();

                return false;
            }

            return true;
        }
    });

And handle the onActivityResult as below:

@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (mUploadMessage == null) return;
        Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

    else if (requestCode == 101) {
        if (mUploadMessageArr == null) return;
        mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
        mUploadMessageArr = null;
    }

}

@jamonholmgren

@nikilarigela

This issue only comes on old Android devices, It does support ES6 script(It makes sense right).
To work on it just go to babel and parse it.

@jayporta

JavaScript isn’t executing at all for Android 5.0 and under (<= API 21 as ggsrivas also reported) on the app I’m building as well. Inside the script tag, all I’ve put is a JavaScript alert and it won’t fire. 5.1 and above work (an yes you have to avoid ES6 syntax and use polyfills where necessary).

@nikilarigela

@jayporta have u tried with baseUrl=" " baseUrl with empty string.

@ujjwal-sri

Is it sure that it js inside the <script> tag of html file won’t run on android studio for API level <=21.

@nikilarigela

@orchuban

@nikilarigela

@orchoban i think you have to mention this in href path asset:/filename

@orchuban

I check it and Expo change the files name of the images and all the files in asset folder.
so I can’t get them in src attributes from HTML file(WebView).

@nikilarigela

@orchoban I think the best way is to host it and load it with URL rather than loading with local assets.

@SaeedZhiany

Confirmed not working on android emulator but works with real device …

solution : ignore your emulator 💯

@if4lcon
I have tested on 3 real android devices and the problem still exists on android 5.1.
Android 7.1.1: works fine
Android 5.1.1: works fine
Android 5.1: not working

also emulators with any android version not working.

@camilo86

I’m running an android emulator 7.1.1 and it is working fine, but running on android device 4.4.4 does not work

@facebook
facebook

locked as resolved and limited conversation to collaborators

Dec 11, 2019

WebView (opens new window) is a view that display web pages inside your application. By this you can add your own URL.

# Troubleshooting WebView by printing console messages or by remote debugging

# Printing webview console messages to logcat

To handle console messages from web page you can override onConsoleMessage (opens new window) in WebChromeClient (opens new window):

And set it in your activity or fragment:

So this sample page:

will write log ‘test message’ to logcat:

WebView: test message sample.html:4

console.info(), console.warn() and console.error() are also supported by chrome-client.

# Remote debugging android devices with Chrome

Your can remote debug webview based application from you desktop Chrome.

# Enable USB debugging on your Android device

On your Android device, open up Settings, find the Developer options section, and enable USB debugging.

# Connect and discover your Android device

Open page in chrome following page: chrome://inspect/#devices (opens new window)

From the Inspect Devices dialog, select your device and press inspect. A new instance of Chrome’s DevTools opens up on your development machine.

More detailed guideline and description of DevTools can be found on developers.google.com (opens new window)

# Communication from Javascript to Java (Android)

Android Activity

Java Javascript Handler

Web Page, Javascript call

Extra Tip

Passing in a complex data structure, a possible solution is use JSON.

On the Android side use your favorite JSON parser ie: JSONObject

# Communication from Java to Javascript

Basic Example

# JavaScript alert dialogs in WebView — How to make them work

By default, WebView does not implement JavaScript alert dialogs, ie. alert() will do nothing. In order to make you need to firstly enable JavaScript (obviously..), and then set a WebChromeClient to handle requests for alert dialogs from the page:

Here, we override onJsAlert, and then we call through to the super implementation, which gives us a standard Android dialog. You can also use the message and URL yourself, for example if you want to create a custom styled dialog or if you want to log them.

# Open dialer example

If the web page a contains phone number you can make a call using your phone’s dialer. This code checks for the url which starts with tel: then make an intent to open dialer and you can make a call to the clicked phone number:

# Open Local File / Create dynamic content in Webview

Layout.xml

Load data into WebViewToDisplay

Please don’t forget to add permission in your Android manifest file

Вступление

WebView — это представление, отображающее веб-страницы внутри вашего приложения. При этом вы можете добавить свой собственный URL.

замечания

Не забудьте добавить разрешение в файл манифеста Android

<uses-permission android:name="android.permission.INTERNET" /> 

Диалоги оповещений JavaScript в WebView — как заставить их работать

По умолчанию WebView не реализует диалоговые окна предупреждения JavaScript, то есть. alert() ничего не сделает. Чтобы вам было нужно сначала включить JavaScript (очевидно ..), а затем установить WebChromeClient для обработки запросов на диалоговые окна предупреждений со страницы:

webView.setWebChromeClient(new WebChromeClient() {
    //Other methods for your WebChromeClient here, if needed..

    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }
});

Здесь мы переопределяем onJsAlert , а затем onJsAlert к супер-реализации, которая дает нам стандартный диалог Android. Вы также можете использовать сообщение и URL-адрес самостоятельно, например, если вы хотите создать пользовательское диалоговое окно стиля или если вы хотите их зарегистрировать.

Общение с Javascript на Java (Android)

Активность Android

package com.example.myapp;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class WebViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        WebView webView = new WebView(this);
        setContentView(webView);

       /* 
        *   Note the label Android, this is used in the Javascript side of things
        *   You can of course change this.
        */
        webView.addJavascriptInterface(new JavascriptHandler(), "Android");
    
        webView.loadUrl("http://example.com");
    }
}

Обработчик Java Javascript

import android.webkit.JavascriptInterface;

public class JavascriptHandler {

    /**
     *  Key point here is the annotation @JavascriptInterface
     *
     */
    @JavascriptInterface
    public void jsCallback() {
       // Do something
    }

    @JavascriptInterface
    public void jsCallbackTwo(String dummyData) {
       // Do something
    }
}

Веб-страница, вызов Javascript

<script>
... 
Android.jsCallback();
...
Android.jsCallback('hello test');
...
</script>

Дополнительный совет

При переходе в сложную структуру данных возможным решением является использование JSON.

Android.jsCallback('{ "fake-var" : "fake-value", "fake-array" : [0,1,2] }');

На стороне Android используйте свой любимый парсер JSON, то есть: JSONObject

Общение с Java на Javascript

Основной пример

package com.example.myapp;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class WebViewActivity extends Activity {
    
    private Webview webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       webView = new WebView(this);
       webView.getSettings().setJavaScriptEnabled(true);

       setContentView(webView);

       webView.loadUrl("http://example.com");

       /*
        * Invoke Javascript function
        */
       webView.loadUrl("javascript:testJsFunction('Hello World!')");
    }

   /**
    * Invoking a Javascript function
    */
   public void doSomething() {
     this.webView.loadUrl("javascript:testAnotherFunction('Hello World Again!')");
   }
}

Пример открытого набора

Если веб-страница a содержит номер телефона, вы можете позвонить, используя дозвон вашего телефона. Этот код проверяет URL-адрес, который начинается с tel: затем сделайте намерение открыть дозвонщик, и вы можете позвонить по нажатому номеру телефона:

public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.startsWith("tel:")) { 
            Intent intent = new Intent(Intent.ACTION_DIAL,
                    Uri.parse(url)); 
            startActivity(intent); 
    }else if(url.startsWith("http:") || url.startsWith("https:")) {
        view.loadUrl(url);
    }
    return true;
}

Печать сообщений консоли webview для logcat

Чтобы обрабатывать console сообщения с веб-страницы, вы можете переопределить onConsoleMessage в WebChromeClient :

final class ChromeClient extends WebChromeClient {
    @Override
    public boolean onConsoleMessage(ConsoleMessage msg) {
        Log.d(
            "WebView", 
            String.format("%s %s:%d", msg.message(), msg.lineNumber(), msg.sourceId())
        );
        return true;
    }
}

И установите его в своей деятельности или фрагменте:

webView.setWebChromeClient(new ChromeClient());

Итак, эта примерная страница:

<html>
<head>
    <script type="text/javascript">
        console.log('test message');
    </script>
</head>
<body>
</body>
</html>

будет записывать журнал «тестовое сообщение» на logcat:

WebView: тестовое сообщение sample.html: 4

console.info() , console.warn() и console.error() также поддерживаются хром-клиентом.

Удаленное отладочное устройство Android с Chrome

Ваш удаленный отлаживающий веб-приложение на основе вашего браузера Chrome.

Включить отладку USB на устройстве Android.

На устройстве Android откройте «Настройки», найдите раздел «Параметры разработчика» и включите USB-отладку.

Подключайтесь и обнаруживайте Android-устройство

Открыть страницу в хроме на следующей странице: chrome: // проверка / # устройств

В диалоговом окне «Inspect Devices» выберите ваше устройство и нажмите « проверить» . На вашем компьютере разработки открывается новый экземпляр DevTools от Chrome.

Более подробное руководство и описание DevTools можно найти на developers.google.com.

Открыть локальный файл / создать динамический контент в Webview

layout.xml

                <WebView
                android:id="@+id/WebViewToDisplay"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:fadeScrollbars="false" />

Загрузка данных в WebViewToDisplay

        WebView webViewDisplay;
        StringBuffer LoadWEb1;

        webViewDisplay = (WebView) findViewById(R.id.WebViewToDisplay);
        LoadWEb1 = new StringBuffer();
        LoadWEb1.append("<html><body><h1>My First Heading</h1><p>My first paragraph.</p>");
        //Sample code to read parameters at run time
        String strName = "Test Paragraph";
        LoadWEb1.append("<br/><p>"+strName+"</p>");
        String result = LoadWEb1.append("</body></html>").toString();
                WebSettings webSettings = webViewDisplay.getSettings();
                webSettings.setJavaScriptEnabled(true);
                webViewDisplay.getSettings().setBuiltInZoomControls(true);
                if (android.os.Build.VERSION.SDK_INT >= 11){
                    webViewDisplay.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                    webViewDisplay.getSettings().setDisplayZoomControls(false);
                }

                webViewDisplay.loadDataWithBaseURL(null, result, "text/html", "utf-8",
                        null);
                //To load local file directly from assets folder use below code
                //webViewDisplay.loadUrl("file:///android_asset/aboutapp.html");

Понравилась статья? Поделить с друзьями:
  • Websocket protocol error
  • Websocket json error
  • Websocket error undefined
  • Websocket error network error 12030 подключение к серверу было неожиданно прервано
  • Websocket error event