Michael Giuffrida | e522d04 | 2018-03-02 07:49:04 | [diff] [blame] | 1 | // 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 | |
| 12 | namespace extensions { |
| 13 | namespace browsertest_util { |
| 14 | |
Mustaq Ahmed | eedcfc9 | 2018-05-09 17:34:53 | [diff] [blame] | 15 | std::string ExecuteScriptInBackgroundPage( |
| 16 | content::BrowserContext* context, |
| 17 | const std::string& extension_id, |
| 18 | const std::string& script, |
| 19 | ScriptUserActivation script_user_activation) { |
Michael Giuffrida | e522d04 | 2018-03-02 07:49:04 | [diff] [blame] | 20 | 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 Ahmed | eedcfc9 | 2018-05-09 17:34:53 | [diff] [blame] | 28 | 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 Giuffrida | e522d04 | 2018-03-02 07:49:04 | [diff] [blame] | 39 | ADD_FAILURE() << "Executing script failed: " << script; |
| 40 | result.clear(); |
| 41 | } |
| 42 | return result; |
| 43 | } |
| 44 | |
| 45 | bool 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 |