1 // Copyright 2015 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 #include "extensions/test/background_page_watcher.h"
7 #include "base/auto_reset.h"
8 #include "base/logging.h"
9 #include "base/run_loop.h"
10 #include "base/scoped_observer.h"
11 #include "content/public/browser/render_process_host.h"
12 #include "content/public/browser/render_view_host.h"
13 #include "content/public/browser/web_contents.h"
14 #include "extensions/browser/extension_host.h"
15 #include "extensions/browser/process_manager.h"
16 #include "extensions/common/extension.h"
18 namespace extensions
{
20 BackgroundPageWatcher::BackgroundPageWatcher(ProcessManager
* process_manager
,
21 const Extension
* extension
)
22 : process_manager_(process_manager
),
23 extension_id_(extension
->id()),
24 is_waiting_for_open_(false),
25 is_waiting_for_close_(false) {}
27 BackgroundPageWatcher::~BackgroundPageWatcher() {}
29 void BackgroundPageWatcher::WaitForOpen() {
30 WaitForOpenState(true);
33 void BackgroundPageWatcher::WaitForClose() {
34 WaitForOpenState(false);
37 void BackgroundPageWatcher::WaitForOpenState(bool wait_for_open
) {
38 if (IsBackgroundPageOpen() == wait_for_open
)
40 ScopedObserver
<ProcessManager
, ProcessManagerObserver
> observer(this);
41 observer
.Add(process_manager_
);
42 bool* flag
= wait_for_open
? &is_waiting_for_open_
: &is_waiting_for_close_
;
43 base::AutoReset
<bool> set_flag(flag
, true);
44 base::RunLoop run_loop
;
45 base::AutoReset
<base::Closure
> set_quit_run_loop(&quit_run_loop_
,
46 run_loop
.QuitClosure());
48 DCHECK_EQ(wait_for_open
, IsBackgroundPageOpen());
51 bool BackgroundPageWatcher::IsBackgroundPageOpen() {
53 process_manager_
->GetBackgroundHostForExtension(extension_id_
);
56 content::RenderProcessHost
* rph
=
57 host
->host_contents()->GetRenderProcessHost();
58 return rph
&& rph
->HasConnection();
61 void BackgroundPageWatcher::OnExtensionFrameRegistered(
62 const std::string
& extension_id
,
63 content::RenderFrameHost
* rfh
) {
64 if (is_waiting_for_open_
&& extension_id
== extension_id_
&&
65 IsBackgroundPageOpen())
69 void BackgroundPageWatcher::OnExtensionFrameUnregistered(
70 const std::string
& extension_id
,
71 content::RenderFrameHost
* rfh
) {
72 if (is_waiting_for_close_
&& extension_id
== extension_id_
&&
73 !IsBackgroundPageOpen())
77 } // namespace extensions