2 * Copyright (C) 2008, 2009 Google Inc. All rights reserved.
3 * Copyright (C) 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2014 Opera Software ASA. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #include "bindings/core/v8/ScriptController.h"
36 #include "bindings/core/v8/BindingSecurity.h"
37 #include "bindings/core/v8/NPV8Object.h"
38 #include "bindings/core/v8/ScriptCallStackFactory.h"
39 #include "bindings/core/v8/ScriptSourceCode.h"
40 #include "bindings/core/v8/ScriptValue.h"
41 #include "bindings/core/v8/V8Binding.h"
42 #include "bindings/core/v8/V8Event.h"
43 #include "bindings/core/v8/V8GCController.h"
44 #include "bindings/core/v8/V8HTMLElement.h"
45 #include "bindings/core/v8/V8NPObject.h"
46 #include "bindings/core/v8/V8PerContextData.h"
47 #include "bindings/core/v8/V8ScriptRunner.h"
48 #include "bindings/core/v8/V8Window.h"
49 #include "bindings/core/v8/WindowProxy.h"
50 #include "bindings/core/v8/npruntime_impl.h"
51 #include "bindings/core/v8/npruntime_priv.h"
52 #include "core/dom/Document.h"
53 #include "core/dom/Node.h"
54 #include "core/dom/ScriptableDocumentParser.h"
55 #include "core/events/Event.h"
56 #include "core/events/EventListener.h"
57 #include "core/frame/LocalDOMWindow.h"
58 #include "core/frame/LocalFrame.h"
59 #include "core/frame/Settings.h"
60 #include "core/frame/UseCounter.h"
61 #include "core/frame/csp/ContentSecurityPolicy.h"
62 #include "core/html/HTMLPlugInElement.h"
63 #include "core/inspector/InspectorInstrumentation.h"
64 #include "core/inspector/InspectorTraceEvents.h"
65 #include "core/inspector/ScriptCallStack.h"
66 #include "core/loader/DocumentLoader.h"
67 #include "core/loader/FrameLoader.h"
68 #include "core/loader/FrameLoaderClient.h"
69 #include "core/loader/ProgressTracker.h"
70 #include "core/plugins/PluginView.h"
71 #include "platform/NotImplemented.h"
72 #include "platform/TraceEvent.h"
73 #include "platform/UserGestureIndicator.h"
74 #include "platform/Widget.h"
75 #include "platform/weborigin/SecurityOrigin.h"
76 #include "public/platform/Platform.h"
77 #include "wtf/CurrentTime.h"
78 #include "wtf/StdLibExtras.h"
79 #include "wtf/StringExtras.h"
80 #include "wtf/text/CString.h"
81 #include "wtf/text/StringBuilder.h"
82 #include "wtf/text/TextPosition.h"
86 bool ScriptController::canAccessFromCurrentOrigin(LocalFrame *frame)
90 v8::Isolate* isolate = toIsolate(frame);
91 return !isolate->InContext() || BindingSecurity::shouldAllowAccessToFrame(isolate, frame);
94 ScriptController::ScriptController(LocalFrame* frame)
97 , m_isolate(v8::Isolate::GetCurrent())
98 , m_windowProxy(WindowProxy::create(frame, DOMWrapperWorld::mainWorld(), m_isolate))
99 , m_windowScriptNPObject(0)
103 ScriptController::~ScriptController()
107 void ScriptController::trace(Visitor* visitor)
110 visitor->trace(m_frame);
111 visitor->trace(m_windowProxy);
112 visitor->trace(m_isolatedWorlds);
116 void ScriptController::clearScriptObjects()
118 PluginObjectMap::iterator it = m_pluginObjects.begin();
119 for (; it != m_pluginObjects.end(); ++it) {
120 _NPN_UnregisterObject(it->value);
121 _NPN_ReleaseObject(it->value);
123 m_pluginObjects.clear();
125 if (m_windowScriptNPObject) {
126 // Dispose of the underlying V8 object before releasing our reference
127 // to it, so that if a plugin fails to release it properly we will
128 // only leak the NPObject wrapper, not the object, its document, or
129 // anything else they reference.
130 disposeUnderlyingV8Object(m_isolate, m_windowScriptNPObject);
131 _NPN_ReleaseObject(m_windowScriptNPObject);
132 m_windowScriptNPObject = 0;
136 void ScriptController::clearForClose()
138 double start = currentTime();
139 m_windowProxy->clearForClose();
140 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
141 iter->value->clearForClose();
142 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearForClose", (currentTime() - start) * 1000, 0, 10000, 50);
145 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
147 m_windowProxy->updateSecurityOrigin(origin);
150 v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8::Value> info[])
152 // Keep LocalFrame (and therefore ScriptController) alive.
153 RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
154 return ScriptController::callFunction(m_frame->document(), function, receiver, argc, info, m_isolate);
157 v8::Local<v8::Value> ScriptController::callFunction(ExecutionContext* context, v8::Handle<v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8::Value> info[], v8::Isolate* isolate)
159 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "FunctionCall", "data", devToolsTraceEventData(isolate, context, function));
160 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
161 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
162 InspectorInstrumentationCookie cookie;
163 if (InspectorInstrumentation::timelineAgentEnabled(context)) {
167 GetDevToolsFunctionInfo(function, isolate, scriptId, resourceName, lineNumber);
168 cookie = InspectorInstrumentation::willCallFunction(context, scriptId, resourceName, lineNumber);
171 v8::Local<v8::Value> result = V8ScriptRunner::callFunction(function, context, receiver, argc, info, isolate);
173 InspectorInstrumentation::didCallFunction(cookie);
177 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Handle<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus corsStatus, double* compilationFinishTime)
179 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(m_frame, source.url().string(), source.startLine()));
180 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
181 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
182 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willEvaluateScript(m_frame, source.url().string(), source.startLine());
184 v8::Local<v8::Value> result;
186 V8CacheOptions v8CacheOptions(V8CacheOptionsOff);
187 if (m_frame->settings())
188 v8CacheOptions = m_frame->settings()->v8CacheOptions();
190 // Isolate exceptions that occur when compiling and executing
191 // the code. These exceptions should not interfere with
192 // javascript code we might evaluate from C++ when returning
194 v8::TryCatch tryCatch;
195 tryCatch.SetVerbose(true);
197 v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(source, m_isolate, corsStatus, v8CacheOptions);
199 if (compilationFinishTime) {
200 *compilationFinishTime = WTF::monotonicallyIncreasingTime();
202 // Keep LocalFrame (and therefore ScriptController) alive.
203 RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
204 result = V8ScriptRunner::runCompiledScript(m_isolate, script, m_frame->document());
205 ASSERT(!tryCatch.HasCaught() || result.IsEmpty());
208 InspectorInstrumentation::didEvaluateScript(cookie);
209 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
214 bool ScriptController::initializeMainWorld()
216 if (m_windowProxy->isContextInitialized())
218 return windowProxy(DOMWrapperWorld::mainWorld())->isContextInitialized();
221 WindowProxy* ScriptController::existingWindowProxy(DOMWrapperWorld& world)
223 if (world.isMainWorld())
224 return m_windowProxy->isContextInitialized() ? m_windowProxy.get() : 0;
226 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
227 if (iter == m_isolatedWorlds.end())
229 return iter->value->isContextInitialized() ? iter->value.get() : 0;
232 WindowProxy* ScriptController::windowProxy(DOMWrapperWorld& world)
234 WindowProxy* windowProxy = nullptr;
235 if (world.isMainWorld()) {
236 windowProxy = m_windowProxy.get();
238 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
239 if (iter != m_isolatedWorlds.end()) {
240 windowProxy = iter->value.get();
242 OwnPtrWillBeRawPtr<WindowProxy> isolatedWorldWindowProxy = WindowProxy::create(m_frame, world, m_isolate);
243 windowProxy = isolatedWorldWindowProxy.get();
244 m_isolatedWorlds.set(world.worldId(), isolatedWorldWindowProxy.release());
247 if (!windowProxy->isContextInitialized() && windowProxy->initializeIfNeeded() && world.isMainWorld())
248 m_frame->loader().dispatchDidClearWindowObjectInMainWorld();
252 bool ScriptController::shouldBypassMainWorldCSP()
254 v8::HandleScope handleScope(m_isolate);
255 v8::Handle<v8::Context> context = m_isolate->GetCurrentContext();
256 if (context.IsEmpty() || !toDOMWindow(context))
258 DOMWrapperWorld& world = DOMWrapperWorld::current(m_isolate);
259 return world.isIsolatedWorld() ? world.isolatedWorldHasContentSecurityPolicy() : false;
262 TextPosition ScriptController::eventHandlerPosition() const
264 ScriptableDocumentParser* parser = m_frame->document()->scriptableDocumentParser();
266 return parser->textPosition();
267 return TextPosition::minimumPosition();
270 // Create a V8 object with an interceptor of NPObjectPropertyGetter.
271 void ScriptController::bindToWindowObject(LocalFrame* frame, const String& key, NPObject* object)
273 ScriptState* scriptState = ScriptState::forMainWorld(frame);
274 if (!scriptState->contextIsValid())
277 ScriptState::Scope scope(scriptState);
278 v8::Handle<v8::Object> value = createV8ObjectForNPObject(m_isolate, object, 0);
280 // Attach to the global object.
281 scriptState->context()->Global()->Set(v8String(m_isolate, key), value);
284 void ScriptController::enableEval()
286 if (!m_windowProxy->isContextInitialized())
288 v8::HandleScope handleScope(m_isolate);
289 m_windowProxy->context()->AllowCodeGenerationFromStrings(true);
292 void ScriptController::disableEval(const String& errorMessage)
294 if (!m_windowProxy->isContextInitialized())
296 v8::HandleScope handleScope(m_isolate);
297 v8::Local<v8::Context> v8Context = m_windowProxy->context();
298 v8Context->AllowCodeGenerationFromStrings(false);
299 v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
302 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
306 if (!widget->isPluginView())
309 v8::HandleScope handleScope(m_isolate);
310 v8::Local<v8::Object> scriptableObject = toPluginView(widget)->scriptableObject(m_isolate);
312 if (scriptableObject.IsEmpty())
315 // LocalFrame Memory Management for NPObjects
316 // -------------------------------------
317 // NPObjects are treated differently than other objects wrapped by JS.
318 // NPObjects can be created either by the browser (e.g. the main
319 // window object) or by the plugin (the main plugin object
320 // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
321 // is especially careful to ensure NPObjects terminate at frame teardown because
322 // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
324 // The LocalFrame maintains a list of plugin objects (m_pluginObjects)
325 // which it can use to quickly find the wrapped embed object.
327 // Inside the NPRuntime, we've added a few methods for registering
328 // wrapped NPObjects. The purpose of the registration is because
329 // javascript garbage collection is non-deterministic, yet we need to
330 // be able to tear down the plugin objects immediately. When an object
331 // is registered, javascript can use it. When the object is destroyed,
332 // or when the object's "owning" object is destroyed, the object will
333 // be un-registered, and the javascript engine must not use it.
335 // Inside the javascript engine, the engine can keep a reference to the
336 // NPObject as part of its wrapper. However, before accessing the object
337 // it must consult the _NPN_Registry.
339 if (isWrappedNPObject(scriptableObject)) {
340 // Track the plugin object. We've been given a reference to the object.
341 m_pluginObjects.set(widget, v8ObjectToNPObject(scriptableObject));
344 return SharedPersistent<v8::Object>::create(scriptableObject, m_isolate);
347 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
349 PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
350 if (it == m_pluginObjects.end())
352 _NPN_UnregisterObject(it->value);
353 _NPN_ReleaseObject(it->value);
354 m_pluginObjects.remove(it);
357 V8Extensions& ScriptController::registeredExtensions()
359 DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
363 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
365 const V8Extensions& extensions = registeredExtensions();
366 for (size_t i = 0; i < extensions.size(); ++i) {
367 if (extensions[i] == extension)
370 v8::RegisterExtension(extension);
371 registeredExtensions().append(extension);
374 static NPObject* createNoScriptObject()
380 static NPObject* createScriptObject(LocalFrame* frame, v8::Isolate* isolate)
382 ScriptState* scriptState = ScriptState::forMainWorld(frame);
383 if (!scriptState->contextIsValid())
384 return createNoScriptObject();
386 ScriptState::Scope scope(scriptState);
387 LocalDOMWindow* window = frame->domWindow();
388 v8::Handle<v8::Value> global = toV8(window, scriptState->context()->Global(), scriptState->isolate());
389 ASSERT(global->IsObject());
390 return npCreateV8ScriptObject(isolate, 0, v8::Handle<v8::Object>::Cast(global), window);
393 NPObject* ScriptController::windowScriptNPObject()
395 if (m_windowScriptNPObject)
396 return m_windowScriptNPObject;
398 if (canExecuteScripts(NotAboutToExecuteScript)) {
399 // JavaScript is enabled, so there is a JavaScript window object.
400 // Return an NPObject bound to the window object.
401 m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
402 _NPN_RegisterObject(m_windowScriptNPObject, 0);
404 // JavaScript is not enabled, so we cannot bind the NPObject to the
405 // JavaScript window object. Instead, we create an NPObject of a
406 // different class, one which is not bound to a JavaScript object.
407 m_windowScriptNPObject = createNoScriptObject();
409 return m_windowScriptNPObject;
412 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
414 // Can't create NPObjects when JavaScript is disabled.
415 if (!canExecuteScripts(NotAboutToExecuteScript))
416 return createNoScriptObject();
418 ScriptState* scriptState = ScriptState::forMainWorld(m_frame);
419 if (!scriptState->contextIsValid())
420 return createNoScriptObject();
422 ScriptState::Scope scope(scriptState);
423 LocalDOMWindow* window = m_frame->domWindow();
424 v8::Handle<v8::Value> v8plugin = toV8(plugin, scriptState->context()->Global(), scriptState->isolate());
425 if (!v8plugin->IsObject())
426 return createNoScriptObject();
428 return npCreateV8ScriptObject(scriptState->isolate(), 0, v8::Handle<v8::Object>::Cast(v8plugin), window);
431 void ScriptController::clearWindowProxy()
433 double start = currentTime();
434 // V8 binding expects ScriptController::clearWindowProxy only be called
435 // when a frame is loading a new page. This creates a new context for the new page.
437 // The V8 context must be available for |clearScriptObjects()|.
438 // The below call must be before |clearForNavigation()| which disposes the V8 context.
439 clearScriptObjects();
440 m_windowProxy->clearForNavigation();
441 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
442 iter->value->clearForNavigation();
443 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowProxy", (currentTime() - start) * 1000, 0, 10000, 50);
446 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
448 v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
451 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
453 for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
454 WindowProxy* isolatedWorldWindowProxy = it->value.get();
455 SecurityOrigin* origin = isolatedWorldWindowProxy->world().isolatedWorldSecurityOrigin();
458 if (!isolatedWorldWindowProxy->isContextInitialized())
460 result.append(std::pair<ScriptState*, SecurityOrigin*>(isolatedWorldWindowProxy->scriptState(), origin));
464 void ScriptController::setWorldDebugId(int worldId, int debuggerId)
466 ASSERT(debuggerId > 0);
467 bool isMainWorld = worldId == MainWorldId;
468 WindowProxy* windowProxy = 0;
470 windowProxy = m_windowProxy.get();
472 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(worldId);
473 if (iter != m_isolatedWorlds.end())
474 windowProxy = iter->value.get();
476 if (!windowProxy || !windowProxy->isContextInitialized())
478 v8::HandleScope scope(m_isolate);
479 v8::Local<v8::Context> context = windowProxy->context();
480 const char* worldName = isMainWorld ? "page" : "injected";
481 V8PerContextDebugData::setContextDebugData(context, worldName, debuggerId);
484 void ScriptController::updateDocument()
486 // For an uninitialized main window windowProxy, do not incur the cost of context initialization.
487 if (!m_windowProxy->isGlobalInitialized())
490 if (!initializeMainWorld())
491 windowProxy(DOMWrapperWorld::mainWorld())->updateDocument();
494 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
496 windowProxy(DOMWrapperWorld::mainWorld())->namedItemAdded(doc, name);
499 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
501 windowProxy(DOMWrapperWorld::mainWorld())->namedItemRemoved(doc, name);
504 static bool isInPrivateScriptIsolateWorld(v8::Isolate* isolate)
506 v8::Handle<v8::Context> context = isolate->GetCurrentContext();
507 return !context.IsEmpty() && toDOMWindow(context) && DOMWrapperWorld::current(isolate).isPrivateScriptIsolatedWorld();
510 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
512 // For performance reasons, we check isInPrivateScriptIsolateWorld() only if
513 // canExecuteScripts is going to return false.
515 if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
516 if (isInPrivateScriptIsolateWorld(m_isolate))
518 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
519 if (reason == AboutToExecuteScript)
520 m_frame->document()->addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Blocked script execution in '" + m_frame->document()->url().elidedString() + "' because the document's frame is sandboxed and the 'allow-scripts' permission is not set."));
524 if (m_frame->document() && m_frame->document()->isViewSource()) {
525 ASSERT(m_frame->document()->securityOrigin()->isUnique());
529 Settings* settings = m_frame->settings();
530 const bool allowed = m_frame->loader().client()->allowScript(settings && settings->scriptEnabled())
531 || isInPrivateScriptIsolateWorld(m_isolate);
532 if (!allowed && reason == AboutToExecuteScript)
533 m_frame->loader().client()->didNotAllowScript();
537 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
539 if (!protocolIsJavaScript(url))
543 || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
546 if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
547 m_frame->loader().progress().progressStarted();
549 // We need to hold onto the LocalFrame here because executing script can
550 // destroy the frame.
551 RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
552 RefPtrWillBeRawPtr<Document> ownerDocument(m_frame->document());
554 const int javascriptSchemeLength = sizeof("javascript:") - 1;
556 bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
558 String decodedURL = decodeURLEscapeSequences(url.string());
559 v8::HandleScope handleScope(m_isolate);
560 v8::Local<v8::Value> result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
562 // If executing script caused this frame to be removed from the page, we
563 // don't want to try to replace its document!
564 if (!m_frame->page())
567 if (result.IsEmpty() || !result->IsString())
569 String scriptResult = toCoreString(v8::Handle<v8::String>::Cast(result));
571 // We're still in a frame, so there should be a DocumentLoader.
572 ASSERT(m_frame->document()->loader());
573 if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
576 m_frame->loader().replaceDocumentWhileExecutingJavaScriptURL(scriptResult, ownerDocument.get());
580 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
582 v8::HandleScope handleScope(m_isolate);
583 evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
586 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, double* compilationFinishTime)
588 v8::HandleScope handleScope(m_isolate);
589 evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled, compilationFinishTime);
592 v8::Local<v8::Value> ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
594 return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
597 v8::Local<v8::Value> ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy, double* compilationFinishTime)
599 if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
600 return v8::Local<v8::Value>();
602 String sourceURL = sourceCode.url();
603 const String* savedSourceURL = m_sourceURL;
604 m_sourceURL = &sourceURL;
606 v8::EscapableHandleScope handleScope(m_isolate);
607 v8::Handle<v8::Context> context = toV8Context(m_frame, DOMWrapperWorld::mainWorld());
608 if (context.IsEmpty())
609 return v8::Local<v8::Value>();
611 ScriptState* scriptState = ScriptState::from(context);
612 ScriptState::Scope scope(scriptState);
614 RefPtrWillBeRawPtr<LocalFrame> protect(m_frame.get());
615 if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
616 m_frame->loader().didAccessInitialDocument();
618 OwnPtr<ScriptSourceCode> maybeProcessedSourceCode = InspectorInstrumentation::preprocess(m_frame, sourceCode);
619 const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
621 v8::Local<v8::Value> object = executeScriptAndReturnValue(scriptState->context(), sourceCodeToCompile, corsStatus, compilationFinishTime);
622 m_sourceURL = savedSourceURL;
624 if (object.IsEmpty())
625 return v8::Local<v8::Value>();
627 return handleScope.Escape(object);
630 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<v8::Local<v8::Value> >* results)
634 RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
635 WindowProxy* isolatedWorldWindowProxy = windowProxy(*world);
636 if (!isolatedWorldWindowProxy->isContextInitialized())
639 ScriptState* scriptState = isolatedWorldWindowProxy->scriptState();
640 v8::EscapableHandleScope handleScope(scriptState->isolate());
641 ScriptState::Scope scope(scriptState);
642 v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
644 for (size_t i = 0; i < sources.size(); ++i) {
645 v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(scriptState->context(), sources[i]);
646 if (evaluationResult.IsEmpty())
647 evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
648 resultArray->Set(i, evaluationResult);
652 for (size_t i = 0; i < resultArray->Length(); ++i)
653 results->append(handleScope.Escape(resultArray->Get(i)));