summaryrefslogtreecommitdiffstats
path: root/chrome/test/chromedriver/javascript_dialog_manager.cc
blob: ed8aa70c84e5d35e70533a3fc43d6c3fad4b7d6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/chromedriver/javascript_dialog_manager.h"

#include "base/logging.h"
#include "base/values.h"
#include "chrome/test/chromedriver/devtools_client.h"
#include "chrome/test/chromedriver/status.h"

JavaScriptDialogManager::JavaScriptDialogManager(DevToolsClient* client)
    : client_(client) {
  client_->AddListener(this);
}

JavaScriptDialogManager::~JavaScriptDialogManager() {
}

bool JavaScriptDialogManager::IsDialogOpen() {
  client_->HandleReceivedEvents();
  return !unhandled_dialog_queue_.empty();
}

Status JavaScriptDialogManager::GetDialogMessage(std::string* message) {
  if (!IsDialogOpen())
    return Status(kNoAlertOpen);

  *message = unhandled_dialog_queue_.front();
  return Status(kOk);
}

Status JavaScriptDialogManager::HandleDialog(bool accept,
                                             const std::string& text) {
  if (!IsDialogOpen())
    return Status(kNoAlertOpen);

  base::DictionaryValue params;
  params.SetBoolean("accept", accept);
  params.SetString("promptText", text);
  Status status = client_->SendCommand("Page.handleJavaScriptDialog", params);
  if (status.IsError())
    return status;

  // Remove a dialog from the queue. Need to check the queue is not empty here,
  // because it could have been cleared during waiting for the command
  // response.
  if (unhandled_dialog_queue_.size())
    unhandled_dialog_queue_.pop_front();
  return Status(kOk);
}

Status JavaScriptDialogManager::OnConnected() {
  unhandled_dialog_queue_.clear();
  base::DictionaryValue params;
  return client_->SendCommand("Page.enable", params);
}

void JavaScriptDialogManager::OnEvent(const std::string& method,
                                      const base::DictionaryValue& params) {
  if (method == "Page.javascriptDialogOpening") {
    std::string message;
    if (!params.GetString("message", &message)) {
      LOG(ERROR) << "dialog event missing or invalid 'message'";
    }
    unhandled_dialog_queue_.push_back(message);
  } else if (method == "Page.javascriptDialogClosing") {
    // Inspector only sends this event when all dialogs have been closed.
    // Clear the unhandled queue in case the user closed a dialog manually.
    unhandled_dialog_queue_.clear();
  }
}