| 1 | // Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | package org.chromium.android_webview.test.util; |
| 6 | |
| 7 | import org.chromium.content.browser.ContentViewCore; |
| 8 | |
| 9 | /** |
| 10 | * This class is used to be notified when a javascript event happened. It add itself as |
| 11 | * a javascript interface, so it could be notified by javascript when needed. |
| 12 | * |
| 13 | * 1. Call register() is to add a javascript interface into ContentViewCore. |
| 14 | * 2. Using waitForEnvent() to wait javascript event. |
| 15 | * 3. In javascript call notifyJava() when you want Java side know something is done. |
| 16 | */ |
| 17 | public class JavascriptEventObserver { |
| 18 | private Object mEvent = new Object(); |
| 19 | private boolean mHappened; |
| 20 | |
| 21 | /** |
| 22 | * Register into javascript, must be called in UI thread. |
| 23 | * |
| 24 | * @param contentViewCore |
| 25 | * @param name the name of object used in javascript |
| 26 | */ |
| 27 | public void register(ContentViewCore contentViewCore, String name) { |
| 28 | contentViewCore.addPossiblyUnsafeJavascriptInterface(this, name, null); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Wait for the javascript event happen for specific time, there is no timeout parameter, |
| 33 | * return true if the event happened. |
| 34 | */ |
| 35 | public boolean waitForEvent(long time) throws InterruptedException { |
| 36 | synchronized (mEvent) { |
| 37 | if (mHappened) return mHappened; |
| 38 | mEvent.wait(time); |
| 39 | boolean happened = mHappened; |
| 40 | mHappened = false; |
| 41 | return happened; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Wait for the javascript event happen, there is no timeout parameter, you usually |
| 47 | * should depend on unit test's timeout. |
| 48 | */ |
| 49 | public void waitForEvent() throws InterruptedException { |
| 50 | synchronized (mEvent) { |
| 51 | if (mHappened) return; |
| 52 | while (!mHappened) { |
| 53 | mEvent.wait(); |
| 54 | } |
| 55 | mHappened = false; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Javascript should call this method by name.notifyJava, the name is the |name| |
| 61 | * parameter of register() method. |
| 62 | */ |
| 63 | public void notifyJava() { |
| 64 | synchronized (mEvent) { |
| 65 | mHappened = true; |
| 66 | mEvent.notify(); |
| 67 | } |
| 68 | } |
| 69 | } |