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.android_webview.test.util;
7 import android.test.InstrumentationTestCase;
8 import android.util.Log;
10 import junit.framework.Assert;
12 import org.chromium.android_webview.AwContents;
13 import org.chromium.content.browser.test.util.CallbackHelper;
14 import org.chromium.content.browser.test.util.Criteria;
15 import org.chromium.content.browser.test.util.CriteriaHelper;
16 import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnEvaluateJavaScriptResultHelper;
18 import java.util.concurrent.atomic.AtomicInteger;
20 // Collection of functions for JavaScript-based interactions with a page.
21 public class JSUtils {
22 private static final int WAIT_TIMEOUT_SECONDS = 2;
23 private static final int CHECK_INTERVAL = 100;
25 public static void clickOnLinkUsingJs(
26 final InstrumentationTestCase testCase,
27 final AwContents awContents,
28 final OnEvaluateJavaScriptResultHelper onEvaluateJavaScriptResultHelper,
29 final String linkId) throws Exception {
31 Assert.assertTrue(CriteriaHelper.pollForCriteria(new Criteria() {
33 public boolean isSatisfied() {
35 String linkIsNotNull = executeJavaScriptAndWaitForResult(testCase, awContents,
36 onEvaluateJavaScriptResultHelper,
37 "document.getElementById('" + linkId + "') != null");
38 return linkIsNotNull.equals("true");
39 } catch (Throwable t) {
41 Assert.fail("Failed to check if DOM is loaded: " + t.toString());
45 }, WAIT_TIMEOUT_SECONDS * 1000, CHECK_INTERVAL));
47 testCase.getInstrumentation().runOnMainSync(new Runnable() {
50 awContents.getContentViewCore().evaluateJavaScript(
51 "var evObj = document.createEvent('Events'); " +
52 "evObj.initEvent('click', true, false); " +
53 "document.getElementById('" + linkId + "').dispatchEvent(evObj);" +
54 "console.log('element with id [" + linkId + "] clicked');",
60 public static String executeJavaScriptAndWaitForResult(
61 InstrumentationTestCase testCase,
62 final AwContents awContents,
63 final OnEvaluateJavaScriptResultHelper onEvaluateJavaScriptResultHelper,
64 final String code) throws Exception {
65 testCase.getInstrumentation().runOnMainSync(new Runnable() {
68 onEvaluateJavaScriptResultHelper.evaluateJavaScript(
69 awContents.getContentViewCore(), code);
72 onEvaluateJavaScriptResultHelper.waitUntilHasValue();
73 Assert.assertTrue("Failed to retrieve JavaScript evaluation results.",
74 onEvaluateJavaScriptResultHelper.hasValue());
75 return onEvaluateJavaScriptResultHelper.getJsonResultAndClear();