summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/extension_webnavigation_api.cc
blob: c7471f9734f3d201e1d7a41c3335d34f08a5550d (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
// Copyright (c) 2011 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.

// Implements the Chrome Extensions WebNavigation API.

#include "chrome/browser/extensions/extension_webnavigation_api.h"

#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_webnavigation_api_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
#include "net/base/net_errors.h"

namespace keys = extension_webnavigation_api_constants;

namespace {

typedef std::map<TabContents*, ExtensionWebNavigationTabObserver*>
    TabObserverMap;
static base::LazyInstance<TabObserverMap> g_tab_observer(
    base::LINKER_INITIALIZED);

// URL schemes for which we'll send events.
const char* kValidSchemes[] = {
  chrome::kHttpScheme,
  chrome::kHttpsScheme,
  chrome::kFileScheme,
  chrome::kFtpScheme,
  chrome::kJavaScriptScheme,
  chrome::kDataScheme,
};

// Returns the frame ID as it will be passed to the extension:
// 0 if the navigation happens in the main frame, or the frame ID
// modulo 32 bits otherwise.
// Keep this in sync with the GetFrameId() function in
// extension_webrequest_api.cc.
int GetFrameId(bool is_main_frame, int64 frame_id) {
  return is_main_frame ? 0 : static_cast<int>(frame_id);
}

// Returns |time| as milliseconds since the epoch.
double MilliSecondsFromTime(const base::Time& time) {
  return 1000 * time.ToDoubleT();
}

// Dispatches events to the extension message service.
void DispatchEvent(content::BrowserContext* browser_context,
                   const char* event_name,
                   const std::string& json_args) {
  Profile* profile = Profile::FromBrowserContext(browser_context);
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, profile, GURL());
  }
}

// Constructs and dispatches an onBeforeNavigate event.
void DispatchOnBeforeNavigate(TabContents* tab_contents,
                              int64 frame_id,
                              bool is_main_frame,
                              const GURL& validated_url) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetString(keys::kUrlKey, validated_url.spec());
  dict->SetInteger(keys::kFrameIdKey, GetFrameId(is_main_frame, frame_id));
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(tab_contents->browser_context(),
                keys::kOnBeforeNavigate,
                json_args);
}

// Constructs and dispatches an onCommitted or onReferenceFragmentUpdated
// event.
void DispatchOnCommitted(const char* event_name,
                         TabContents* tab_contents,
                         int64 frame_id,
                         bool is_main_frame,
                         const GURL& url,
                         PageTransition::Type transition_type) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetString(keys::kUrlKey, url.spec());
  dict->SetInteger(keys::kFrameIdKey, GetFrameId(is_main_frame, frame_id));
  dict->SetString(keys::kTransitionTypeKey,
                  PageTransition::CoreTransitionString(transition_type));
  ListValue* qualifiers = new ListValue();
  if (transition_type & PageTransition::CLIENT_REDIRECT)
    qualifiers->Append(Value::CreateStringValue("client_redirect"));
  if (transition_type & PageTransition::SERVER_REDIRECT)
    qualifiers->Append(Value::CreateStringValue("server_redirect"));
  if (transition_type & PageTransition::FORWARD_BACK)
    qualifiers->Append(Value::CreateStringValue("forward_back"));
  if (transition_type & PageTransition::FROM_ADDRESS_BAR)
    qualifiers->Append(Value::CreateStringValue("from_address_bar"));
  dict->Set(keys::kTransitionQualifiersKey, qualifiers);
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(tab_contents->browser_context(), event_name, json_args);
}

// Constructs and dispatches an onDOMContentLoaded event.
void DispatchOnDOMContentLoaded(TabContents* tab_contents,
                                const GURL& url,
                                bool is_main_frame,
                                int64 frame_id) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetString(keys::kUrlKey, url.spec());
  dict->SetInteger(keys::kFrameIdKey, GetFrameId(is_main_frame, frame_id));
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(tab_contents->browser_context(),
                keys::kOnDOMContentLoaded,
                json_args);
}

// Constructs and dispatches an onCompleted event.
void DispatchOnCompleted(TabContents* tab_contents,
                         const GURL& url,
                         bool is_main_frame,
                         int64 frame_id) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetString(keys::kUrlKey, url.spec());
  dict->SetInteger(keys::kFrameIdKey, GetFrameId(is_main_frame, frame_id));
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(tab_contents->browser_context(), keys::kOnCompleted, json_args);
}

// Constructs and dispatches an onCreatedNavigationTarget event.
void DispatchOnCreatedNavigationTarget(
    TabContents* tab_contents,
    content::BrowserContext* browser_context,
    int64 source_frame_id,
    bool source_frame_is_main_frame,
    TabContents* target_tab_contents,
    const GURL& target_url) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kSourceTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetInteger(keys::kSourceFrameIdKey,
      GetFrameId(source_frame_is_main_frame, source_frame_id));
  dict->SetString(keys::kUrlKey, target_url.possibly_invalid_spec());
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(target_tab_contents));
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(
      browser_context, keys::kOnCreatedNavigationTarget, json_args);
}

// Constructs and dispatches an onErrorOccurred event.
void DispatchOnErrorOccurred(TabContents* tab_contents,
                             const GURL& url,
                             int64 frame_id,
                             bool is_main_frame,
                             int error_code) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger(keys::kTabIdKey,
                   ExtensionTabUtil::GetTabId(tab_contents));
  dict->SetString(keys::kUrlKey, url.spec());
  dict->SetInteger(keys::kFrameIdKey, GetFrameId(is_main_frame, frame_id));
  dict->SetString(keys::kErrorKey, net::ErrorToString(error_code));
  dict->SetDouble(keys::kTimeStampKey, MilliSecondsFromTime(base::Time::Now()));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  DispatchEvent(tab_contents->browser_context(),
                keys::kOnErrorOccurred,
                json_args);
}

}  // namespace


// FrameNavigationState -------------------------------------------------------

// static
bool FrameNavigationState::allow_extension_scheme_ = false;

FrameNavigationState::FrameNavigationState()
    : main_frame_id_(-1) {
}

FrameNavigationState::~FrameNavigationState() {}

bool FrameNavigationState::CanSendEvents(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  if (frame_state == frame_state_map_.end() ||
      frame_state->second.error_occurred) {
    return false;
  }
  return IsValidUrl(frame_state->second.url);
}

bool FrameNavigationState::IsValidUrl(const GURL& url) const {
  for (unsigned i = 0; i < arraysize(kValidSchemes); ++i) {
    if (url.scheme() == kValidSchemes[i])
      return true;
  }
  // Allow about:blank.
  if (url.spec() == chrome::kAboutBlankURL)
    return true;
  if (allow_extension_scheme_ && url.scheme() == chrome::kExtensionScheme)
    return true;
  return false;
}

void FrameNavigationState::TrackFrame(int64 frame_id,
                                      const GURL& url,
                                      bool is_main_frame,
                                      bool is_error_page) {
  if (is_main_frame) {
    frame_state_map_.clear();
    frame_ids_.clear();
  }
  FrameState& frame_state = frame_state_map_[frame_id];
  frame_state.error_occurred = is_error_page;
  frame_state.url = url;
  frame_state.is_main_frame = is_main_frame;
  frame_state.is_navigating = true;
  frame_state.is_committed = false;
  if (is_main_frame) {
    main_frame_id_ = frame_id;
  }
  frame_ids_.insert(frame_id);
}

bool FrameNavigationState::IsValidFrame(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  return (frame_state != frame_state_map_.end());
}

GURL FrameNavigationState::GetUrl(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  if (frame_state == frame_state_map_.end()) {
    NOTREACHED();
    return GURL();
  }
  return frame_state->second.url;
}

bool FrameNavigationState::IsMainFrame(int64 frame_id) const {
  return main_frame_id_ != -1 && main_frame_id_ == frame_id;
}

int64 FrameNavigationState::GetMainFrameID() const {
  return main_frame_id_;
}

void FrameNavigationState::SetErrorOccurredInFrame(int64 frame_id) {
  DCHECK(frame_state_map_.find(frame_id) != frame_state_map_.end());
  frame_state_map_[frame_id].error_occurred = true;
}

bool FrameNavigationState::GetErrorOccurredInFrame(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  return (frame_state == frame_state_map_.end() ||
          frame_state->second.error_occurred);
}

void FrameNavigationState::SetNavigationCompleted(int64 frame_id) {
  DCHECK(frame_state_map_.find(frame_id) != frame_state_map_.end());
  frame_state_map_[frame_id].is_navigating = false;
}

bool FrameNavigationState::GetNavigationCompleted(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  return (frame_state == frame_state_map_.end() ||
          !frame_state->second.is_navigating);
}

void FrameNavigationState::SetNavigationCommitted(int64 frame_id) {
  DCHECK(frame_state_map_.find(frame_id) != frame_state_map_.end());
  frame_state_map_[frame_id].is_committed = true;
}

bool FrameNavigationState::GetNavigationCommitted(int64 frame_id) const {
  FrameIdToStateMap::const_iterator frame_state =
      frame_state_map_.find(frame_id);
  return (frame_state != frame_state_map_.end() &&
          frame_state->second.is_committed);
}


// ExtensionWebNavigtionEventRouter -------------------------------------------

ExtensionWebNavigationEventRouter::PendingTabContents::PendingTabContents()
    : source_tab_contents(NULL),
      source_frame_id(0),
      source_frame_is_main_frame(false),
      target_tab_contents(NULL),
      target_url() {
}

ExtensionWebNavigationEventRouter::PendingTabContents::PendingTabContents(
    TabContents* source_tab_contents,
    int64 source_frame_id,
    bool source_frame_is_main_frame,
    TabContents* target_tab_contents,
    const GURL& target_url)
    : source_tab_contents(source_tab_contents),
      source_frame_id(source_frame_id),
      source_frame_is_main_frame(source_frame_is_main_frame),
      target_tab_contents(target_tab_contents),
      target_url(target_url) {
}

ExtensionWebNavigationEventRouter::PendingTabContents::~PendingTabContents() {}

ExtensionWebNavigationEventRouter::ExtensionWebNavigationEventRouter(
    Profile* profile) : profile_(profile) {}

ExtensionWebNavigationEventRouter::~ExtensionWebNavigationEventRouter() {}

void ExtensionWebNavigationEventRouter::Init() {
  if (registrar_.IsEmpty()) {
    registrar_.Add(this,
                   content::NOTIFICATION_RETARGETING,
                   Source<content::BrowserContext>(profile_));
    registrar_.Add(this,
                   content::NOTIFICATION_TAB_ADDED,
                   NotificationService::AllSources());
    registrar_.Add(this,
                   content::NOTIFICATION_TAB_CONTENTS_DESTROYED,
                   NotificationService::AllSources());
  }
}

void ExtensionWebNavigationEventRouter::Observe(
    int type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  switch (type) {
    case content::NOTIFICATION_RETARGETING:
      Retargeting(Details<const content::RetargetingDetails>(details).ptr());
      break;

    case content::NOTIFICATION_TAB_ADDED:
      TabAdded(Details<TabContents>(details).ptr());
      break;

    case content::NOTIFICATION_TAB_CONTENTS_DESTROYED:
      TabDestroyed(Source<TabContents>(source).ptr());
      break;

    default:
      NOTREACHED();
  }
}

void ExtensionWebNavigationEventRouter::Retargeting(
    const content::RetargetingDetails* details) {
  if (details->source_frame_id == 0)
    return;
  ExtensionWebNavigationTabObserver* tab_observer =
      ExtensionWebNavigationTabObserver::Get(details->source_tab_contents);
  if (!tab_observer) {
    NOTREACHED();
    return;
  }
  const FrameNavigationState& frame_navigation_state =
      tab_observer->frame_navigation_state();

  if (!frame_navigation_state.CanSendEvents(details->source_frame_id))
    return;

  // If the TabContents was created as a response to an IPC from a renderer, it
  // doesn't yet have a wrapper, and we need to delay the extension event until
  // the TabContents is fully initialized.
  if (TabContentsWrapper::GetCurrentWrapperForContents(
      details->target_tab_contents) == NULL) {
    pending_tab_contents_[details->target_tab_contents] =
        PendingTabContents(
            details->source_tab_contents,
            details->source_frame_id,
            frame_navigation_state.IsMainFrame(details->source_frame_id),
            details->target_tab_contents,
            details->target_url);
  } else {
    DispatchOnCreatedNavigationTarget(
        details->source_tab_contents,
        details->target_tab_contents->browser_context(),
        details->source_frame_id,
        frame_navigation_state.IsMainFrame(details->source_frame_id),
        details->target_tab_contents,
        details->target_url);
  }
}

void ExtensionWebNavigationEventRouter::TabAdded(TabContents* tab_contents) {
  std::map<TabContents*, PendingTabContents>::iterator iter =
      pending_tab_contents_.find(tab_contents);
  if (iter == pending_tab_contents_.end())
    return;

  DispatchOnCreatedNavigationTarget(
      iter->second.source_tab_contents,
      iter->second.target_tab_contents->browser_context(),
      iter->second.source_frame_id,
      iter->second.source_frame_is_main_frame,
      iter->second.target_tab_contents,
      iter->second.target_url);
  pending_tab_contents_.erase(iter);
}

void ExtensionWebNavigationEventRouter::TabDestroyed(
    TabContents* tab_contents) {
  pending_tab_contents_.erase(tab_contents);
  for (std::map<TabContents*, PendingTabContents>::iterator i =
           pending_tab_contents_.begin(); i != pending_tab_contents_.end(); ) {
    if (i->second.source_tab_contents == tab_contents)
      pending_tab_contents_.erase(i++);
    else
      ++i;
  }
}

// ExtensionWebNavigationTabObserver ------------------------------------------

ExtensionWebNavigationTabObserver::ExtensionWebNavigationTabObserver(
    TabContents* tab_contents)
    : TabContentsObserver(tab_contents) {
  g_tab_observer.Get().insert(TabObserverMap::value_type(tab_contents, this));
}

ExtensionWebNavigationTabObserver::~ExtensionWebNavigationTabObserver() {}

// static
ExtensionWebNavigationTabObserver* ExtensionWebNavigationTabObserver::Get(
    TabContents* tab_contents) {
  TabObserverMap::iterator i = g_tab_observer.Get().find(tab_contents);
  return i == g_tab_observer.Get().end() ? NULL : i->second;
}

void ExtensionWebNavigationTabObserver::DidStartProvisionalLoadForFrame(
    int64 frame_id,
    bool is_main_frame,
    const GURL& validated_url,
    bool is_error_page,
    RenderViewHost* render_view_host) {
  // Ignore navigations of sub frames, if the main frame isn't committed yet.
  // This might happen if a sub frame triggers a navigation for both the main
  // frame and itself. Since the sub frame is about to be deleted, and there's
  // no way for an extension to tell that these navigations belong to an old
  // frame, we just suppress the events here.
  int64 main_frame_id = navigation_state_.GetMainFrameID();
  if (!is_main_frame &&
      !navigation_state_.GetNavigationCommitted(main_frame_id)) {
    return;
  }

  navigation_state_.TrackFrame(frame_id,
                               validated_url,
                               is_main_frame,
                               is_error_page);
  if (!navigation_state_.CanSendEvents(frame_id))
    return;
  DispatchOnBeforeNavigate(
      tab_contents(), frame_id, is_main_frame, validated_url);
}

void ExtensionWebNavigationTabObserver::DidCommitProvisionalLoadForFrame(
    int64 frame_id,
    bool is_main_frame,
    const GURL& url,
    PageTransition::Type transition_type) {
  if (!navigation_state_.CanSendEvents(frame_id))
    return;

  bool is_reference_fragment_navigation =
      IsReferenceFragmentNavigation(frame_id, url);

  // Update the URL as it might have changed.
  navigation_state_.TrackFrame(frame_id,
                               url,
                               is_main_frame,
                               false);
  navigation_state_.SetNavigationCommitted(frame_id);

  if (is_reference_fragment_navigation) {
    DispatchOnCommitted(
        keys::kOnReferenceFragmentUpdated,
        tab_contents(),
        frame_id,
        is_main_frame,
        url,
        transition_type);
    navigation_state_.SetNavigationCompleted(frame_id);
  } else {
    DispatchOnCommitted(
        keys::kOnCommitted,
        tab_contents(),
        frame_id,
        is_main_frame,
        url,
        transition_type);
  }
}

void ExtensionWebNavigationTabObserver::DidFailProvisionalLoad(
    int64 frame_id,
    bool is_main_frame,
    const GURL& validated_url,
    int error_code,
    const string16& error_description) {
  if (!navigation_state_.CanSendEvents(frame_id))
    return;
  navigation_state_.SetErrorOccurredInFrame(frame_id);
  DispatchOnErrorOccurred(
      tab_contents(), validated_url, frame_id, is_main_frame, error_code);
}

void ExtensionWebNavigationTabObserver::DocumentLoadedInFrame(
    int64 frame_id) {
  if (!navigation_state_.CanSendEvents(frame_id))
    return;
  DispatchOnDOMContentLoaded(tab_contents(),
                             navigation_state_.GetUrl(frame_id),
                             navigation_state_.IsMainFrame(frame_id),
                             frame_id);
}

void ExtensionWebNavigationTabObserver::DidFinishLoad(
    int64 frame_id) {
  if (!navigation_state_.CanSendEvents(frame_id))
    return;
  navigation_state_.SetNavigationCompleted(frame_id);
  DispatchOnCompleted(tab_contents(),
                      navigation_state_.GetUrl(frame_id),
                      navigation_state_.IsMainFrame(frame_id),
                      frame_id);
}

void ExtensionWebNavigationTabObserver::DidOpenRequestedURL(
    TabContents* new_contents,
    const GURL& url,
    const GURL& referrer,
    WindowOpenDisposition disposition,
    PageTransition::Type transition,
    int64 source_frame_id) {
  if (!navigation_state_.CanSendEvents(source_frame_id))
    return;

  // We only send the onCreatedNavigationTarget if we end up creating a new
  // window.
  if (disposition != SINGLETON_TAB &&
      disposition != NEW_FOREGROUND_TAB &&
      disposition != NEW_BACKGROUND_TAB &&
      disposition != NEW_POPUP &&
      disposition != NEW_WINDOW &&
      disposition != OFF_THE_RECORD)
    return;

  DispatchOnCreatedNavigationTarget(
      tab_contents(),
      new_contents->browser_context(),
      source_frame_id,
      navigation_state_.IsMainFrame(source_frame_id),
      new_contents,
      url);
}

void ExtensionWebNavigationTabObserver::TabContentsDestroyed(
    TabContents* tab) {
  g_tab_observer.Get().erase(tab);
  for (FrameNavigationState::const_iterator frame = navigation_state_.begin();
       frame != navigation_state_.end(); ++frame) {
    if (!navigation_state_.GetNavigationCompleted(*frame) &&
        navigation_state_.CanSendEvents(*frame)) {
      DispatchOnErrorOccurred(
        tab,
        navigation_state_.GetUrl(*frame),
        *frame,
        navigation_state_.IsMainFrame(*frame),
        net::ERR_ABORTED);
    }
  }
}

// See also NavigationController::IsURLInPageNavigation.
bool ExtensionWebNavigationTabObserver::IsReferenceFragmentNavigation(
    int64 frame_id,
    const GURL& url) {
  GURL existing_url = navigation_state_.GetUrl(frame_id);
  if (existing_url == url)
    return false;

  url_canon::Replacements<char> replacements;
  replacements.ClearRef();
  return existing_url.ReplaceComponents(replacements) ==
      url.ReplaceComponents(replacements);
}

bool GetFrameFunction::RunImpl() {
  DictionaryValue* details;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details));
  DCHECK(details);

  int tab_id;
  int frame_id;
  EXTENSION_FUNCTION_VALIDATE(details->GetInteger(keys::kTabIdKey, &tab_id));
  EXTENSION_FUNCTION_VALIDATE(
      details->GetInteger(keys::kFrameIdKey, &frame_id));

  result_.reset(Value::CreateNullValue());

  TabContentsWrapper* wrapper;
  if (!ExtensionTabUtil::GetTabById(
        tab_id, profile(), include_incognito(), NULL, NULL, &wrapper, NULL) ||
      !wrapper) {
    return true;
  }

  TabContents* tab_contents = wrapper->tab_contents();
  ExtensionWebNavigationTabObserver* observer =
      ExtensionWebNavigationTabObserver::Get(tab_contents);
  DCHECK(observer);

  const FrameNavigationState& frame_navigation_state =
      observer->frame_navigation_state();

  if (frame_id == 0)
    frame_id = frame_navigation_state.GetMainFrameID();
  if (!frame_navigation_state.IsValidFrame(frame_id))
    return true;

  GURL frame_url = frame_navigation_state.GetUrl(frame_id);
  if (!frame_navigation_state.IsValidUrl(frame_url))
    return true;

  DictionaryValue* resultDict = new DictionaryValue();
  resultDict->SetString(keys::kUrlKey, frame_url.spec());
  resultDict->SetBoolean(
      keys::kErrorOccurredKey,
      frame_navigation_state.GetErrorOccurredInFrame(frame_id));
  result_.reset(resultDict);
  return true;
}

bool GetAllFramesFunction::RunImpl() {
  DictionaryValue* details;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details));
  DCHECK(details);

  int tab_id;
  EXTENSION_FUNCTION_VALIDATE(details->GetInteger(keys::kTabIdKey, &tab_id));

  result_.reset(Value::CreateNullValue());

  TabContentsWrapper* wrapper;
  if (!ExtensionTabUtil::GetTabById(
        tab_id, profile(), include_incognito(), NULL, NULL, &wrapper, NULL) ||
      !wrapper) {
    return true;
  }

  TabContents* tab_contents = wrapper->tab_contents();
  ExtensionWebNavigationTabObserver* observer =
      ExtensionWebNavigationTabObserver::Get(tab_contents);
  DCHECK(observer);

  const FrameNavigationState& navigation_state =
      observer->frame_navigation_state();

  ListValue* resultList = new ListValue();
  for (FrameNavigationState::const_iterator frame = navigation_state.begin();
       frame != navigation_state.end(); ++frame) {
    GURL frame_url = navigation_state.GetUrl(*frame);
    if (!navigation_state.IsValidUrl(frame_url))
      continue;
    DictionaryValue* frameDict = new DictionaryValue();
    frameDict->SetString(keys::kUrlKey, frame_url.spec());
    frameDict->SetInteger(
        keys::kFrameIdKey,
        GetFrameId(navigation_state.IsMainFrame(*frame), *frame));
    frameDict->SetBoolean(
        keys::kErrorOccurredKey,
        navigation_state.GetErrorOccurredInFrame(*frame));
    resultList->Append(frameDict);
  }
  result_.reset(resultList);
  return true;
}