1 // Copyright 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 static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
9 import junit.framework.Assert;
11 import org.chromium.base.ThreadUtils;
12 import org.chromium.content.browser.ContentViewCore;
13 import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.TimeoutException;
19 * Collection of JavaScript utilities.
21 public class JavaScriptUtils {
22 private static final long EVALUATION_TIMEOUT_SECONDS = scaleTimeout(5);
25 * Executes the given snippet of JavaScript code within the given ContentView.
26 * Returns the result of its execution in JSON format.
28 public static String executeJavaScriptAndWaitForResult(
29 ContentViewCore viewCore, String code) throws InterruptedException, TimeoutException {
30 return executeJavaScriptAndWaitForResult(
31 viewCore, code, EVALUATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
35 * Executes the given snippet of JavaScript code within the given ContentViewCore.
36 * Does not depend on ContentView and TestCallbackHelperContainer.
37 * Returns the result of its execution in JSON format.
39 public static String executeJavaScriptAndWaitForResult(
40 final ContentViewCore viewCore,
43 final TimeUnit timeoutUnits)
44 throws InterruptedException, TimeoutException {
45 final OnEvaluateJavaScriptResultHelper helper = new OnEvaluateJavaScriptResultHelper();
46 // Calling this from the UI thread causes it to time-out: the UI thread being blocked won't
47 // have a chance to process the JavaScript eval response).
48 Assert.assertFalse("Executing JavaScript should be done from the test thread, "
49 + " not the UI thread", ThreadUtils.runningOnUiThread());
50 ThreadUtils.runOnUiThread(new Runnable() {
53 helper.evaluateJavaScript(viewCore, code);
56 helper.waitUntilHasValue(timeout, timeoutUnits);
57 Assert.assertTrue("Failed to retrieve JavaScript evaluation results.", helper.hasValue());
58 return helper.getJsonResultAndClear();
62 * Executes the given snippet of JavaScript code but does not wait for the result.
64 public static void executeJavaScript(final ContentViewCore viewCore, final String code) {
65 ThreadUtils.runOnUiThread(new Runnable() {
68 viewCore.evaluateJavaScript(code, null);