Send event of scrolling from ScrollView to the WebView JavaScript code

GitHub: https://github.com/Pulimet/ScrollViewEventTest

First in onCreate() we will set our WebView:

private WebView mWebView;
private ScrollView mScrollView;
public static final long DELAY_TIME = 1000;
private long mTime;
...
mWebView = findViewById(R.id.webView);
mWebView.loadUrl("http:///www.alexandroid.net");

Enable JavaScript:

WebSettings webViewSettings = mWebView.getSettings();
webViewSettings.setJavaScriptEnabled(true);

Create a method that would invoke our JavaScript code:

private void invokeJavaScriptCode(String code) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    mWebView.evaluateJavascript(code, null);
  } else {
    mWebView.loadUrl(String.format("javascript:%s", code));
  }
}

Set on page loaded listener and invoke onPageLoaded method:

mWebView.setWebViewClient(new WebViewClient() {
  @Override
  public void onPageFinished(WebView view, String url) {
    onPageLoaded();
  }
});

And when page loaded, invoke JavaScript code that would listen for scroll event and print it to log:

private void onPageLoaded() {
  invokeJavaScriptCode("" +
      "jQuery(document).ready(function($){" +
          "$(window).scroll(function(event, data) {" +
              "console.log(\"LOG: top: \" + data.top + \"  left: \" + data.left);" +
          "});" +
      "});");
}

To check that our events are received (in WebView logs) we need to setWebChromeClient and override onConsoleMessage(…) method:

mWebView.setWebChromeClient(new WebChromeClient() {
  @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
      Log.d("WebViewLogs", consoleMessage.message());
      return true;
    }
});

Finally in onCreate() add ScrollView on scroll listener that would trigger an event with one second delay:

private void setScrollViewListener() {
  mScrollView = findViewById(R.id.scrollView);
  mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
      if (mTime + DELAY_TIME <span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>< System.currentTimeMillis()) {
        mTime = System.currentTimeMillis();
        sendScrollEvent(mScrollView.getScrollY(), mScrollView.getScrollX());
      }
    }
  });
}

Sending scroll event:

private void sendScrollEvent(int top, int left) {
  invokeJavaScriptCode(
    String.format("" +
        "jQuery(document).ready(" +
            "function($){" +
                "$(window).trigger(\"scroll\", [{top: %d , left: %d}]);" +
            "}" +
        ");"
    , top, left)
  );
}

XML code:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        tools:ignore="ScrollViewSize">

        <TextView
            android:id="@+id/tvTop"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:background="@color/colorPrimaryDark"
            android:gravity="center"
            android:text="@string/some_content_is_here"
            android:textColor="@color/colorAccent"
            android:textSize="20sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <WebView
            android:id="@+id/webView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvTop"/>

        <TextView
            android:id="@+id/tvBottom"
            android:layout_width="0dp"
            android:layout_height="200dp"
            android:background="@color/colorPrimaryDark"
            android:gravity="center"
            android:text="@string/some_content_is_here"
            android:textColor="@color/colorAccent"
            android:textSize="20sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/webView"/>

    </android.support.constraint.ConstraintLayout>
</ScrollView>

Yea!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.