2 * Copyright (C) 2008, 2009 Google Inc. All rights reserved.
3 * Copyright (C) 2009 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "bindings/v8/ScriptController.h"
36 #include "V8HTMLElement.h"
38 #include "bindings/v8/BindingSecurity.h"
39 #include "bindings/v8/NPV8Object.h"
40 #include "bindings/v8/ScriptCallStackFactory.h"
41 #include "bindings/v8/ScriptSourceCode.h"
42 #include "bindings/v8/ScriptValue.h"
43 #include "bindings/v8/V8Binding.h"
44 #include "bindings/v8/V8GCController.h"
45 #include "bindings/v8/V8NPObject.h"
46 #include "bindings/v8/V8PerContextData.h"
47 #include "bindings/v8/V8ScriptRunner.h"
48 #include "bindings/v8/V8WindowShell.h"
49 #include "bindings/v8/npruntime_impl.h"
50 #include "bindings/v8/npruntime_priv.h"
51 #include "core/dom/Document.h"
52 #include "core/dom/Node.h"
53 #include "core/dom/ScriptableDocumentParser.h"
54 #include "core/events/Event.h"
55 #include "core/events/EventListener.h"
56 #include "core/frame/DOMWindow.h"
57 #include "core/frame/LocalFrame.h"
58 #include "core/frame/Settings.h"
59 #include "core/frame/csp/ContentSecurityPolicy.h"
60 #include "core/html/HTMLPlugInElement.h"
61 #include "core/inspector/InspectorInstrumentation.h"
62 #include "core/inspector/InspectorTraceEvents.h"
63 #include "core/inspector/ScriptCallStack.h"
64 #include "core/loader/DocumentLoader.h"
65 #include "core/loader/FrameLoader.h"
66 #include "core/loader/FrameLoaderClient.h"
67 #include "core/plugins/PluginView.h"
68 #include "platform/NotImplemented.h"
69 #include "platform/TraceEvent.h"
70 #include "platform/UserGestureIndicator.h"
71 #include "platform/Widget.h"
72 #include "platform/weborigin/SecurityOrigin.h"
73 #include "public/platform/Platform.h"
74 #include "wtf/CurrentTime.h"
75 #include "wtf/StdLibExtras.h"
76 #include "wtf/StringExtras.h"
77 #include "wtf/text/CString.h"
78 #include "wtf/text/StringBuilder.h"
79 #include "wtf/text/TextPosition.h"
83 bool ScriptController::canAccessFromCurrentOrigin(LocalFrame *frame)
87 v8::Isolate* isolate = toIsolate(frame);
88 return !isolate->InContext() || BindingSecurity::shouldAllowAccessToFrame(isolate, frame);
91 ScriptController::ScriptController(LocalFrame* frame)
94 , m_isolate(v8::Isolate::GetCurrent())
95 , m_windowShell(V8WindowShell::create(frame, DOMWrapperWorld::mainWorld(), m_isolate))
96 , m_windowScriptNPObject(0)
100 ScriptController::~ScriptController()
102 // V8WindowShell::clearForClose() must be invoked before destruction starts.
103 ASSERT(!m_windowShell->isContextInitialized());
106 void ScriptController::clearScriptObjects()
108 PluginObjectMap::iterator it = m_pluginObjects.begin();
109 for (; it != m_pluginObjects.end(); ++it) {
110 _NPN_UnregisterObject(it->value);
111 _NPN_ReleaseObject(it->value);
113 m_pluginObjects.clear();
115 if (m_windowScriptNPObject) {
116 // Dispose of the underlying V8 object before releasing our reference
117 // to it, so that if a plugin fails to release it properly we will
118 // only leak the NPObject wrapper, not the object, its document, or
119 // anything else they reference.
120 disposeUnderlyingV8Object(m_windowScriptNPObject, m_isolate);
121 _NPN_ReleaseObject(m_windowScriptNPObject);
122 m_windowScriptNPObject = 0;
126 void ScriptController::clearForClose()
128 double start = currentTime();
129 m_windowShell->clearForClose();
130 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
131 iter->value->clearForClose();
132 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearForClose", (currentTime() - start) * 1000, 0, 10000, 50);
135 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
137 m_windowShell->updateSecurityOrigin(origin);
140 v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Value> receiver, int argc, v8::Handle<v8::Value> info[])
142 // Keep LocalFrame (and therefore ScriptController) alive.
143 RefPtr<LocalFrame> protect(m_frame);
144 return ScriptController::callFunction(m_frame->document(), function, receiver, argc, info, m_isolate);
147 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)
149 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "FunctionCall", "data", devToolsTraceEventData(context, function, isolate));
150 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
151 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
152 InspectorInstrumentationCookie cookie;
153 if (InspectorInstrumentation::timelineAgentEnabled(context)) {
157 GetDevToolsFunctionInfo(function, isolate, scriptId, resourceName, lineNumber);
158 cookie = InspectorInstrumentation::willCallFunction(context, scriptId, resourceName, lineNumber);
161 v8::Local<v8::Value> result = V8ScriptRunner::callFunction(function, context, receiver, argc, info, isolate);
163 InspectorInstrumentation::didCallFunction(cookie);
167 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Handle<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus corsStatus)
169 TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(m_frame, source.url().string(), source.startLine()));
170 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
171 // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
172 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willEvaluateScript(m_frame, source.url().string(), source.startLine());
174 v8::Local<v8::Value> result;
176 // Isolate exceptions that occur when compiling and executing
177 // the code. These exceptions should not interfere with
178 // javascript code we might evaluate from C++ when returning
180 v8::TryCatch tryCatch;
181 tryCatch.SetVerbose(true);
183 v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(source, m_isolate, corsStatus);
185 // Keep LocalFrame (and therefore ScriptController) alive.
186 RefPtr<LocalFrame> protect(m_frame);
187 result = V8ScriptRunner::runCompiledScript(script, m_frame->document(), m_isolate);
188 ASSERT(!tryCatch.HasCaught() || result.IsEmpty());
191 InspectorInstrumentation::didEvaluateScript(cookie);
192 TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", "data", InspectorUpdateCountersEvent::data());
197 bool ScriptController::initializeMainWorld()
199 if (m_windowShell->isContextInitialized())
201 return windowShell(DOMWrapperWorld::mainWorld())->isContextInitialized();
204 V8WindowShell* ScriptController::existingWindowShell(DOMWrapperWorld& world)
206 if (world.isMainWorld())
207 return m_windowShell->isContextInitialized() ? m_windowShell.get() : 0;
209 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
210 if (iter == m_isolatedWorlds.end())
212 return iter->value->isContextInitialized() ? iter->value.get() : 0;
215 V8WindowShell* ScriptController::windowShell(DOMWrapperWorld& world)
217 V8WindowShell* shell = 0;
218 if (world.isMainWorld())
219 shell = m_windowShell.get();
221 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world.worldId());
222 if (iter != m_isolatedWorlds.end())
223 shell = iter->value.get();
225 OwnPtr<V8WindowShell> isolatedWorldShell = V8WindowShell::create(m_frame, world, m_isolate);
226 shell = isolatedWorldShell.get();
227 m_isolatedWorlds.set(world.worldId(), isolatedWorldShell.release());
230 if (!shell->isContextInitialized() && shell->initializeIfNeeded() && world.isMainWorld())
231 m_frame->loader().dispatchDidClearWindowObjectInMainWorld();
235 bool ScriptController::shouldBypassMainWorldContentSecurityPolicy()
237 v8::Handle<v8::Context> context = m_isolate->GetCurrentContext();
238 if (context.IsEmpty() || !toDOMWindow(context))
240 DOMWrapperWorld& world = DOMWrapperWorld::current(m_isolate);
241 return world.isIsolatedWorld() ? world.isolatedWorldHasContentSecurityPolicy() : false;
244 TextPosition ScriptController::eventHandlerPosition() const
246 ScriptableDocumentParser* parser = m_frame->document()->scriptableDocumentParser();
248 return parser->textPosition();
249 return TextPosition::minimumPosition();
252 // Create a V8 object with an interceptor of NPObjectPropertyGetter.
253 void ScriptController::bindToWindowObject(LocalFrame* frame, const String& key, NPObject* object)
255 v8::HandleScope handleScope(m_isolate);
257 v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, frame, DOMWrapperWorld::mainWorld());
258 if (v8Context.IsEmpty())
261 v8::Context::Scope scope(v8Context);
263 v8::Handle<v8::Object> value = createV8ObjectForNPObject(object, 0, m_isolate);
265 // Attach to the global object.
266 v8::Handle<v8::Object> global = v8Context->Global();
267 global->Set(v8String(m_isolate, key), value);
270 void ScriptController::enableEval()
272 if (!m_windowShell->isContextInitialized())
274 v8::HandleScope handleScope(m_isolate);
275 m_windowShell->context()->AllowCodeGenerationFromStrings(true);
278 void ScriptController::disableEval(const String& errorMessage)
280 if (!m_windowShell->isContextInitialized())
282 v8::HandleScope handleScope(m_isolate);
283 v8::Local<v8::Context> v8Context = m_windowShell->context();
284 v8Context->AllowCodeGenerationFromStrings(false);
285 v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
288 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
292 if (!widget->isPluginView())
295 NPObject* npObject = toPluginView(widget)->scriptableObject();
299 // LocalFrame Memory Management for NPObjects
300 // -------------------------------------
301 // NPObjects are treated differently than other objects wrapped by JS.
302 // NPObjects can be created either by the browser (e.g. the main
303 // window object) or by the plugin (the main plugin object
304 // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
305 // is especially careful to ensure NPObjects terminate at frame teardown because
306 // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
308 // The LocalFrame maintains a list of plugin objects (m_pluginObjects)
309 // which it can use to quickly find the wrapped embed object.
311 // Inside the NPRuntime, we've added a few methods for registering
312 // wrapped NPObjects. The purpose of the registration is because
313 // javascript garbage collection is non-deterministic, yet we need to
314 // be able to tear down the plugin objects immediately. When an object
315 // is registered, javascript can use it. When the object is destroyed,
316 // or when the object's "owning" object is destroyed, the object will
317 // be un-registered, and the javascript engine must not use it.
319 // Inside the javascript engine, the engine can keep a reference to the
320 // NPObject as part of its wrapper. However, before accessing the object
321 // it must consult the _NPN_Registry.
323 v8::Local<v8::Object> wrapper = createV8ObjectForNPObject(npObject, 0, m_isolate);
325 // Track the plugin object. We've been given a reference to the object.
326 m_pluginObjects.set(widget, npObject);
328 return SharedPersistent<v8::Object>::create(wrapper, m_isolate);
331 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
333 PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
334 if (it == m_pluginObjects.end())
336 _NPN_UnregisterObject(it->value);
337 _NPN_ReleaseObject(it->value);
338 m_pluginObjects.remove(it);
341 V8Extensions& ScriptController::registeredExtensions()
343 DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
347 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
349 const V8Extensions& extensions = registeredExtensions();
350 for (size_t i = 0; i < extensions.size(); ++i) {
351 if (extensions[i] == extension)
354 v8::RegisterExtension(extension);
355 registeredExtensions().append(extension);
358 static NPObject* createNoScriptObject()
364 static NPObject* createScriptObject(LocalFrame* frame, v8::Isolate* isolate)
366 v8::HandleScope handleScope(isolate);
367 v8::Handle<v8::Context> v8Context = toV8Context(isolate, frame, DOMWrapperWorld::mainWorld());
368 if (v8Context.IsEmpty())
369 return createNoScriptObject();
371 v8::Context::Scope scope(v8Context);
372 DOMWindow* window = frame->domWindow();
373 v8::Handle<v8::Value> global = toV8(window, v8::Handle<v8::Object>(), v8Context->GetIsolate());
374 ASSERT(global->IsObject());
376 return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(global), window, isolate);
379 NPObject* ScriptController::windowScriptNPObject()
381 if (m_windowScriptNPObject)
382 return m_windowScriptNPObject;
384 if (canExecuteScripts(NotAboutToExecuteScript)) {
385 // JavaScript is enabled, so there is a JavaScript window object.
386 // Return an NPObject bound to the window object.
387 m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
388 _NPN_RegisterObject(m_windowScriptNPObject, 0);
390 // JavaScript is not enabled, so we cannot bind the NPObject to the
391 // JavaScript window object. Instead, we create an NPObject of a
392 // different class, one which is not bound to a JavaScript object.
393 m_windowScriptNPObject = createNoScriptObject();
395 return m_windowScriptNPObject;
398 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
400 // Can't create NPObjects when JavaScript is disabled.
401 if (!canExecuteScripts(NotAboutToExecuteScript))
402 return createNoScriptObject();
404 v8::HandleScope handleScope(m_isolate);
405 v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
406 if (v8Context.IsEmpty())
407 return createNoScriptObject();
408 v8::Context::Scope scope(v8Context);
410 DOMWindow* window = m_frame->domWindow();
411 v8::Handle<v8::Value> v8plugin = toV8(plugin, v8::Handle<v8::Object>(), v8Context->GetIsolate());
412 if (!v8plugin->IsObject())
413 return createNoScriptObject();
415 return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window, v8Context->GetIsolate());
418 void ScriptController::clearWindowShell()
420 double start = currentTime();
421 // V8 binding expects ScriptController::clearWindowShell only be called
422 // when a frame is loading a new page. This creates a new context for the new page.
423 m_windowShell->clearForNavigation();
424 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
425 iter->value->clearForNavigation();
426 clearScriptObjects();
427 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowShell", (currentTime() - start) * 1000, 0, 10000, 50);
430 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
432 v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
435 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
437 v8::HandleScope handleScope(m_isolate);
438 for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
439 V8WindowShell* isolatedWorldShell = it->value.get();
440 SecurityOrigin* origin = isolatedWorldShell->world().isolatedWorldSecurityOrigin();
443 v8::Local<v8::Context> v8Context = isolatedWorldShell->context();
444 if (v8Context.IsEmpty())
446 ScriptState* scriptState = ScriptState::from(v8Context);
447 result.append(std::pair<ScriptState*, SecurityOrigin*>(scriptState, origin));
451 bool ScriptController::setContextDebugId(int debugId)
454 if (!m_windowShell->isContextInitialized())
456 v8::HandleScope scope(m_isolate);
457 v8::Local<v8::Context> context = m_windowShell->context();
458 return V8PerContextDebugData::setContextDebugData(context, "page", debugId);
461 int ScriptController::contextDebugId(v8::Handle<v8::Context> context)
463 return V8PerContextDebugData::contextDebugId(context);
466 void ScriptController::updateDocument()
468 // For an uninitialized main window shell, do not incur the cost of context initialization during FrameLoader::init().
469 if ((!m_windowShell->isContextInitialized() || !m_windowShell->isGlobalInitialized()) && m_frame->loader().stateMachine()->creatingInitialEmptyDocument())
472 if (!initializeMainWorld())
473 windowShell(DOMWrapperWorld::mainWorld())->updateDocument();
476 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
478 windowShell(DOMWrapperWorld::mainWorld())->namedItemAdded(doc, name);
481 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
483 windowShell(DOMWrapperWorld::mainWorld())->namedItemRemoved(doc, name);
486 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
488 if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
489 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
490 if (reason == AboutToExecuteScript)
491 m_frame->document()->addConsoleMessage(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.");
495 if (m_frame->document() && m_frame->document()->isViewSource()) {
496 ASSERT(m_frame->document()->securityOrigin()->isUnique());
500 Settings* settings = m_frame->settings();
501 const bool allowed = m_frame->loader().client()->allowScript(settings && settings->scriptEnabled());
502 if (!allowed && reason == AboutToExecuteScript)
503 m_frame->loader().client()->didNotAllowScript();
507 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
509 if (!protocolIsJavaScript(url))
513 || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
516 // We need to hold onto the LocalFrame here because executing script can
517 // destroy the frame.
518 RefPtr<LocalFrame> protector(m_frame);
519 RefPtr<Document> ownerDocument(m_frame->document());
521 const int javascriptSchemeLength = sizeof("javascript:") - 1;
523 bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
525 String decodedURL = decodeURLEscapeSequences(url.string());
526 ScriptValue result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
528 // If executing script caused this frame to be removed from the page, we
529 // don't want to try to replace its document!
530 if (!m_frame->page())
534 if (!result.toString(scriptResult))
537 // We're still in a frame, so there should be a DocumentLoader.
538 ASSERT(m_frame->document()->loader());
540 if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
543 // DocumentWriter::replaceDocument can cause the DocumentLoader to get deref'ed and possible destroyed,
544 // so protect it with a RefPtr.
545 if (RefPtr<DocumentLoader> loader = m_frame->document()->loader()) {
546 UseCounter::count(*m_frame->document(), UseCounter::ReplaceDocumentViaJavaScriptURL);
547 loader->replaceDocument(scriptResult, ownerDocument.get());
552 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
554 evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
557 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus)
559 evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled);
562 ScriptValue ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
564 return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
567 ScriptValue ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy)
569 if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
570 return ScriptValue();
572 String sourceURL = sourceCode.url();
573 const String* savedSourceURL = m_sourceURL;
574 m_sourceURL = &sourceURL;
576 v8::HandleScope handleScope(m_isolate);
577 v8::Handle<v8::Context> v8Context = toV8Context(m_isolate, m_frame, DOMWrapperWorld::mainWorld());
578 if (v8Context.IsEmpty())
579 return ScriptValue();
580 v8::Context::Scope scope(v8Context);
582 RefPtr<LocalFrame> protect(m_frame);
583 if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
584 m_frame->loader().didAccessInitialDocument();
586 OwnPtr<ScriptSourceCode> maybeProcessedSourceCode = InspectorInstrumentation::preprocess(m_frame, sourceCode);
587 const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
589 v8::Local<v8::Value> object = executeScriptAndReturnValue(v8Context, sourceCodeToCompile, corsStatus);
590 m_sourceURL = savedSourceURL;
592 if (object.IsEmpty())
593 return ScriptValue();
595 return ScriptValue(ScriptState::from(v8Context), object);
598 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<ScriptValue>* results)
602 v8::HandleScope handleScope(m_isolate);
603 RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
604 V8WindowShell* isolatedWorldShell = windowShell(*world);
605 if (!isolatedWorldShell->isContextInitialized())
608 v8::Local<v8::Context> context = isolatedWorldShell->context();
609 v8::Context::Scope contextScope(context);
610 v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
612 for (size_t i = 0; i < sources.size(); ++i) {
613 v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(context, sources[i]);
614 if (evaluationResult.IsEmpty())
615 evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
616 resultArray->Set(i, evaluationResult);
620 for (size_t i = 0; i < resultArray->Length(); ++i)
621 results->append(ScriptValue(ScriptState::from(context), resultArray->Get(i)));
625 } // namespace WebCore