summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/extensions/user_script_idle_scheduler.cc
blob: f21214f02219530a3ec131c4c5e585b680472318 (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
// 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.

#include "chrome/renderer/extensions/user_script_idle_scheduler.h"

#include "base/message_loop.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/renderer/extension_groups.h"
#include "chrome/renderer/extensions/extension_dispatcher.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/extensions/user_script_slave.h"
#include "content/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace {
// The length of time to wait after the DOM is complete to try and run user
// scripts.
const int kUserScriptIdleTimeoutMs = 200;
}

using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebView;

UserScriptIdleScheduler::UserScriptIdleScheduler(RenderView* render_view,
                                                 WebFrame* frame)
    : RenderViewObserver(render_view),
      ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
      frame_(frame),
      has_run_(false) {
}

UserScriptIdleScheduler::~UserScriptIdleScheduler() {
}

bool UserScriptIdleScheduler::OnMessageReceived(const IPC::Message& message) {
  if (message.type() != ExtensionMsg_ExecuteCode::ID)
    return false;

  // chrome.tabs.executeScript() only supports execution in either the top frame
  // or all frames.  We handle both cases in the top frame.
  WebFrame* main_frame = GetMainFrame();
  if (main_frame && main_frame != frame_)
    return false;

  IPC_BEGIN_MESSAGE_MAP(UserScriptIdleScheduler, message)
    IPC_MESSAGE_HANDLER(ExtensionMsg_ExecuteCode, OnExecuteCode)
  IPC_END_MESSAGE_MAP()
  return true;
}

void UserScriptIdleScheduler::DidFinishDocumentLoad(WebFrame* frame) {
  if (frame != frame_)
    return;

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun),
      kUserScriptIdleTimeoutMs);
}

void UserScriptIdleScheduler::DidFinishLoad(WebFrame* frame) {
  if (frame != frame_)
    return;

  // Ensure that running scripts does not keep any progress UI running.
  MessageLoop::current()->PostTask(FROM_HERE,
      method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun));
}

void UserScriptIdleScheduler::DidStartProvisionalLoad(WebKit::WebFrame* frame) {
  // The frame is navigating, so reset the state since we'll want to inject
  // scripts once the load finishes.
  has_run_ = false;
  method_factory_.RevokeAll();
  while (!pending_code_execution_queue_.empty())
    pending_code_execution_queue_.pop();
}

void UserScriptIdleScheduler::FrameDetached(WebFrame* frame) {
  if (frame != frame_)
    return;

  delete this;
}

void UserScriptIdleScheduler::MaybeRun() {
  if (has_run_)
    return;

  // Note: we must set this before calling ExecuteCodeImpl, because that may
  // result in a synchronous call back into MaybeRun if there is a pending task
  // currently in the queue.
  // http://code.google.com/p/chromium/issues/detail?id=29644
  has_run_ = true;

  if (RenderThread::current()) {  // Will be NULL during unit tests.
    ExtensionDispatcher::Get()->user_script_slave()->InjectScripts(
        frame_, UserScript::DOCUMENT_IDLE);
  }

  while (!pending_code_execution_queue_.empty()) {
    linked_ptr<ExtensionMsg_ExecuteCode_Params>& params =
        pending_code_execution_queue_.front();
    ExecuteCodeImpl(GetMainFrame(), *params);
    pending_code_execution_queue_.pop();
  }
}

void UserScriptIdleScheduler::OnExecuteCode(
    const ExtensionMsg_ExecuteCode_Params& params) {
  WebFrame* main_frame = GetMainFrame();
  if (!main_frame) {
    Send(new ExtensionHostMsg_ExecuteCodeFinished(
         routing_id(), params.request_id, false, ""));
    return;
  }

  if (!has_run_) {
    pending_code_execution_queue_.push(
        linked_ptr<ExtensionMsg_ExecuteCode_Params>(
            new ExtensionMsg_ExecuteCode_Params(params)));
    return;
  }

  ExecuteCodeImpl(main_frame, params);
}

void UserScriptIdleScheduler::ExecuteCodeImpl(
    WebFrame* frame, const ExtensionMsg_ExecuteCode_Params& params) {
  const Extension* extension =
      ExtensionDispatcher::Get()->extensions()->GetByID(
          params.extension_id);

  // Since extension info is sent separately from user script info, they can
  // be out of sync. We just ignore this situation.
  if (!extension) {
    Send(new ExtensionHostMsg_ExecuteCodeFinished(
        routing_id(), params.request_id, true, ""));
    return;
  }

  std::vector<WebFrame*> frame_vector;
  frame_vector.push_back(frame);
  if (params.all_frames)
    GetAllChildFrames(frame, &frame_vector);

  for (std::vector<WebFrame*>::iterator frame_it = frame_vector.begin();
       frame_it != frame_vector.end(); ++frame_it) {
    WebFrame* frame = *frame_it;
    if (params.is_javascript) {
      // We recheck access here in the renderer for extra safety against races
      // with navigation.
      //
      // But different frames can have different URLs, and the extension might
      // only have access to a subset of them. For the top frame, we can
      // immediately send an error and stop because the browser process
      // considers that an error too.
      //
      // For child frames, we just skip ones the extension doesn't have access
      // to and carry on.
      if (!extension->CanExecuteScriptOnPage(frame->url(), NULL, NULL)) {
        if (frame->parent()) {
          continue;
        } else {
          Send(new ExtensionHostMsg_ExecuteCodeFinished(
              routing_id(), params.request_id, false,
              ExtensionErrorUtils::FormatErrorMessage(
                  extension_manifest_errors::kCannotAccessPage,
                  frame->url().spec())));
          return;
        }
      }

      WebScriptSource source(WebString::fromUTF8(params.code));
      if (params.in_main_world) {
        frame->executeScript(source);
      } else {
        std::vector<WebScriptSource> sources;
        sources.push_back(source);
        UserScriptSlave::InsertInitExtensionCode(&sources, params.extension_id);
        frame->executeScriptInIsolatedWorld(
            UserScriptSlave::GetIsolatedWorldId(params.extension_id),
            &sources.front(), sources.size(), EXTENSION_GROUP_CONTENT_SCRIPTS);
      }
    } else {
      frame->insertStyleText(WebString::fromUTF8(params.code), WebString());
    }
  }

  Send(new ExtensionHostMsg_ExecuteCodeFinished(
      routing_id(), params.request_id, true, ""));
}

bool UserScriptIdleScheduler::GetAllChildFrames(
    WebFrame* parent_frame,
    std::vector<WebFrame*>* frames_vector) const {
  if (!parent_frame)
    return false;

  for (WebFrame* child_frame = parent_frame->firstChild(); child_frame;
       child_frame = child_frame->nextSibling()) {
    frames_vector->push_back(child_frame);
    GetAllChildFrames(child_frame, frames_vector);
  }
  return true;
}

WebFrame* UserScriptIdleScheduler::GetMainFrame() {
  WebView* webview = render_view()->webview();
  return webview ? webview->mainFrame() : NULL;
}