1 // Copyright 2014 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/renderer/render_frame_observer_natives.h"
8 #include "base/message_loop/message_loop.h"
9 #include "content/public/renderer/render_frame.h"
10 #include "content/public/renderer/render_frame_observer.h"
11 #include "extensions/renderer/extension_frame_helper.h"
12 #include "extensions/renderer/script_context.h"
14 namespace extensions
{
18 // Deletes itself when done.
19 class LoadWatcher
: public content::RenderFrameObserver
{
21 LoadWatcher(ScriptContext
* context
,
22 content::RenderFrame
* frame
,
23 v8::Local
<v8::Function
> cb
)
24 : content::RenderFrameObserver(frame
),
26 callback_(context
->isolate(), cb
) {
27 if (ExtensionFrameHelper::Get(frame
)->
28 did_create_current_document_element()) {
29 // If the document element is already created, then we can call the
30 // callback immediately (though post it to the message loop so as to not
31 // call it re-entrantly).
32 // The Unretained is safe because this class manages its own lifetime.
33 base::MessageLoop::current()->PostTask(
35 base::Bind(&LoadWatcher::CallbackAndDie
, base::Unretained(this),
40 void DidCreateDocumentElement() override
{ CallbackAndDie(true); }
42 void DidFailProvisionalLoad(const blink::WebURLError
& error
) override
{
43 CallbackAndDie(false);
47 void CallbackAndDie(bool succeeded
) {
48 v8::Isolate
* isolate
= context_
->isolate();
49 v8::HandleScope
handle_scope(isolate
);
50 v8::Local
<v8::Value
> args
[] = {v8::Boolean::New(isolate
, succeeded
)};
51 context_
->CallFunction(v8::Local
<v8::Function
>::New(isolate
, callback_
),
52 arraysize(args
), args
);
56 ScriptContext
* context_
;
57 v8::Global
<v8::Function
> callback_
;
59 DISALLOW_COPY_AND_ASSIGN(LoadWatcher
);
64 RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext
* context
)
65 : ObjectBackedNativeHandler(context
) {
67 "OnDocumentElementCreated",
68 base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated
,
69 base::Unretained(this)));
72 void RenderFrameObserverNatives::OnDocumentElementCreated(
73 const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
74 CHECK(args
.Length() == 2);
75 CHECK(args
[0]->IsInt32());
76 CHECK(args
[1]->IsFunction());
78 int frame_id
= args
[0]->Int32Value();
80 content::RenderFrame
* frame
= content::RenderFrame::FromRoutingID(frame_id
);
82 LOG(WARNING
) << "No render frame found to register LoadWatcher.";
86 new LoadWatcher(context(), frame
, args
[1].As
<v8::Function
>());
88 args
.GetReturnValue().Set(true);
91 } // namespace extensions