blob: 634d3801b42f3fda6ee20a73e5d3fe7bfe7f2353 [file] [log] [blame]
Michael Giuffridae522d042018-03-02 07:49:041// Copyright 2018 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#include "extensions/browser/browsertest_util.h"
6
7#include "content/public/test/browser_test_utils.h"
8#include "extensions/browser/extension_host.h"
9#include "extensions/browser/process_manager.h"
10#include "testing/gtest/include/gtest/gtest.h"
11
12namespace extensions {
13namespace browsertest_util {
14
Mustaq Ahmedeedcfc92018-05-09 17:34:5315std::string ExecuteScriptInBackgroundPage(
16 content::BrowserContext* context,
17 const std::string& extension_id,
18 const std::string& script,
19 ScriptUserActivation script_user_activation) {
Michael Giuffridae522d042018-03-02 07:49:0420 ExtensionHost* host =
21 ProcessManager::Get(context)->GetBackgroundHostForExtension(extension_id);
22 if (!host) {
23 ADD_FAILURE() << "Extension " << extension_id << " has no background page.";
24 return "";
25 }
26
27 std::string result;
Mustaq Ahmedeedcfc92018-05-09 17:34:5328 bool success;
29 if (script_user_activation == ScriptUserActivation::kActivate) {
30 success = content::ExecuteScriptAndExtractString(host->host_contents(),
31 script, &result);
32 } else {
33 DCHECK_EQ(script_user_activation, ScriptUserActivation::kDontActivate);
34 success = content::ExecuteScriptWithoutUserGestureAndExtractString(
35 host->host_contents(), script, &result);
36 }
37
38 if (!success) {
Michael Giuffridae522d042018-03-02 07:49:0439 ADD_FAILURE() << "Executing script failed: " << script;
40 result.clear();
41 }
42 return result;
43}
44
45bool ExecuteScriptInBackgroundPageNoWait(content::BrowserContext* context,
46 const std::string& extension_id,
47 const std::string& script) {
48 ExtensionHost* host =
49 ProcessManager::Get(context)->GetBackgroundHostForExtension(extension_id);
50 if (!host) {
51 ADD_FAILURE() << "Extension " << extension_id << " has no background page.";
52 return false;
53 }
54 content::ExecuteScriptAsync(host->host_contents(), script);
55 return true;
56}
57
58} // namespace browsertest_util
59} // namespace extensions