1 // Copyright (c) 2012 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.
5 package org.chromium.content.browser.test.util;
7 import junit.framework.Assert;
9 import org.chromium.base.ThreadUtils;
10 import org.chromium.content.browser.ContentView;
11 import org.chromium.content.browser.ContentViewCore;
13 import java.util.concurrent.TimeUnit;
14 import java.util.concurrent.TimeoutException;
17 * Collection of JavaScript utilities.
19 public class JavaScriptUtils {
20 private static final long EVALUATION_TIMEOUT_SECONDS = 5;
23 * Executes the given snippet of JavaScript code within the given ContentView.
24 * Returns the result of its execution in JSON format.
26 public static String executeJavaScriptAndWaitForResult(
27 final ContentView view, TestCallbackHelperContainer viewClient,
28 final String code) throws InterruptedException, TimeoutException {
29 return executeJavaScriptAndWaitForResult(
30 view.getContentViewCore(),
31 viewClient.getOnEvaluateJavaScriptResultHelper(),
36 * Executes the given snippet of JavaScript code within the given ContentViewCore.
37 * Does not depend on ContentView and TestCallbackHelperContainer.
38 * Returns the result of its execution in JSON format.
40 public static String executeJavaScriptAndWaitForResult(
41 final ContentViewCore viewCore,
42 final TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper helper,
43 final String code) throws InterruptedException, TimeoutException {
44 return executeJavaScriptAndWaitForResult(
45 viewCore, helper, code, EVALUATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
49 * Executes the given snippet of JavaScript code within the given ContentViewCore.
50 * Does not depend on ContentView and TestCallbackHelperContainer.
51 * Returns the result of its execution in JSON format.
53 public static String executeJavaScriptAndWaitForResult(
54 final ContentViewCore viewCore,
55 final TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper helper,
57 final long timeout, final TimeUnit timeoutUnits)
58 throws InterruptedException, TimeoutException {
59 ThreadUtils.runOnUiThread(new Runnable() {
62 helper.evaluateJavaScript(viewCore, code);
65 helper.waitUntilHasValue(timeout, timeoutUnits);
66 Assert.assertTrue("Failed to retrieve JavaScript evaluation results.", helper.hasValue());
67 return helper.getJsonResultAndClear();
71 * Executes the given snippet of JavaScript code but does not wait for the result.
73 public static void executeJavaScript(final ContentView view, final String code) {
74 ThreadUtils.runOnUiThread(new Runnable() {
77 view.evaluateJavaScript(code);