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/events/ThreadLocalEventNames.h"
57 #include "core/html/HTMLPlugInElement.h"
58 #include "core/inspector/InspectorInstrumentation.h"
59 #include "core/inspector/ScriptCallStack.h"
60 #include "core/loader/DocumentLoader.h"
61 #include "core/loader/FrameLoader.h"
62 #include "core/loader/FrameLoaderClient.h"
63 #include "core/frame/ContentSecurityPolicy.h"
64 #include "core/frame/DOMWindow.h"
65 #include "core/frame/Frame.h"
66 #include "core/frame/Settings.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(Frame *frame)
85 return !v8::Isolate::GetCurrent()->InContext() || BindingSecurity::shouldAllowAccessToFrame(frame);
88 ScriptController::ScriptController(Frame* frame)
91 , m_isolate(v8::Isolate::GetCurrent())
92 , m_windowShell(V8WindowShell::create(frame, mainThreadNormalWorld(), m_isolate))
93 , m_windowScriptNPObject(0)
97 ScriptController::~ScriptController()
99 // V8WindowShell::clearForClose() must be invoked before destruction starts.
100 ASSERT(!m_windowShell->isContextInitialized());
103 void ScriptController::clearScriptObjects()
105 PluginObjectMap::iterator it = m_pluginObjects.begin();
106 for (; it != m_pluginObjects.end(); ++it) {
107 _NPN_UnregisterObject(it->value);
108 _NPN_ReleaseObject(it->value);
110 m_pluginObjects.clear();
112 if (m_windowScriptNPObject) {
113 // Dispose of the underlying V8 object before releasing our reference
114 // to it, so that if a plugin fails to release it properly we will
115 // only leak the NPObject wrapper, not the object, its document, or
116 // anything else they reference.
117 disposeUnderlyingV8Object(m_windowScriptNPObject, m_isolate);
118 _NPN_ReleaseObject(m_windowScriptNPObject);
119 m_windowScriptNPObject = 0;
123 void ScriptController::clearForOutOfMemory()
128 void ScriptController::clearForClose(bool destroyGlobal)
130 m_windowShell->clearForClose(destroyGlobal);
131 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
132 iter->value->clearForClose(destroyGlobal);
133 V8GCController::hintForCollectGarbage();
136 void ScriptController::clearForClose()
138 double start = currentTime();
139 clearForClose(false);
140 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearForClose", (currentTime() - start) * 1000, 0, 10000, 50);
143 void ScriptController::updateSecurityOrigin(SecurityOrigin* origin)
145 m_windowShell->updateSecurityOrigin(origin);
148 v8::Local<v8::Value> ScriptController::callFunction(v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> info[])
150 // Keep Frame (and therefore ScriptController) alive.
151 RefPtr<Frame> protect(m_frame);
152 return ScriptController::callFunction(m_frame->document(), function, receiver, argc, info, m_isolate);
155 static bool resourceInfo(const v8::Handle<v8::Function> function, String& resourceName, int& lineNumber)
157 v8::ScriptOrigin origin = function->GetScriptOrigin();
158 if (origin.ResourceName().IsEmpty()) {
159 resourceName = "undefined";
162 V8TRYCATCH_FOR_V8STRINGRESOURCE_RETURN(V8StringResource<>, stringResourceName, origin.ResourceName(), false);
163 resourceName = stringResourceName;
164 lineNumber = function->GetScriptLineNumber() + 1;
169 v8::Local<v8::Value> ScriptController::callFunction(ExecutionContext* context, v8::Handle<v8::Function> function, v8::Handle<v8::Object> receiver, int argc, v8::Handle<v8::Value> info[], v8::Isolate* isolate)
171 InspectorInstrumentationCookie cookie;
172 if (InspectorInstrumentation::timelineAgentEnabled(context)) {
175 if (!resourceInfo(getBoundFunction(function), resourceName, lineNumber))
176 return v8::Local<v8::Value>();
177 cookie = InspectorInstrumentation::willCallFunction(context, resourceName, lineNumber);
180 v8::Local<v8::Value> result = V8ScriptRunner::callFunction(function, context, receiver, argc, info, isolate);
182 InspectorInstrumentation::didCallFunction(cookie);
186 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Handle<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus corsStatus)
188 v8::Context::Scope scope(context);
190 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willEvaluateScript(m_frame, source.url().isNull() ? String() : source.url().string(), source.startLine());
192 v8::Local<v8::Value> result;
194 // Isolate exceptions that occur when compiling and executing
195 // the code. These exceptions should not interfere with
196 // javascript code we might evaluate from C++ when returning
198 v8::TryCatch tryCatch;
199 tryCatch.SetVerbose(true);
201 v8::Handle<v8::String> code = v8String(m_isolate, source.source());
202 OwnPtr<v8::ScriptData> scriptData = V8ScriptRunner::precompileScript(code, source.resource());
204 // NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at
205 // 1, whereas v8 starts at 0.
206 v8::Handle<v8::Script> script = V8ScriptRunner::compileScript(code, source.url(), source.startPosition(), scriptData.get(), m_isolate, corsStatus);
208 // Keep Frame (and therefore ScriptController) alive.
209 RefPtr<Frame> protect(m_frame);
210 result = V8ScriptRunner::runCompiledScript(script, m_frame->document(), m_isolate);
211 ASSERT(!tryCatch.HasCaught() || result.IsEmpty());
214 InspectorInstrumentation::didEvaluateScript(cookie);
219 bool ScriptController::initializeMainWorld()
221 if (m_windowShell->isContextInitialized())
223 return windowShell(mainThreadNormalWorld())->isContextInitialized();
226 V8WindowShell* ScriptController::existingWindowShell(DOMWrapperWorld* world)
230 if (world->isMainWorld())
231 return m_windowShell->isContextInitialized() ? m_windowShell.get() : 0;
233 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world->worldId());
234 if (iter == m_isolatedWorlds.end())
236 return iter->value->isContextInitialized() ? iter->value.get() : 0;
239 V8WindowShell* ScriptController::windowShell(DOMWrapperWorld* world)
243 V8WindowShell* shell = 0;
244 if (world->isMainWorld())
245 shell = m_windowShell.get();
247 IsolatedWorldMap::iterator iter = m_isolatedWorlds.find(world->worldId());
248 if (iter != m_isolatedWorlds.end())
249 shell = iter->value.get();
251 OwnPtr<V8WindowShell> isolatedWorldShell = V8WindowShell::create(m_frame, world, m_isolate);
252 shell = isolatedWorldShell.get();
253 m_isolatedWorlds.set(world->worldId(), isolatedWorldShell.release());
256 if (!shell->isContextInitialized() && shell->initializeIfNeeded())
257 m_frame->loader().dispatchDidClearWindowObjectInWorld(world);
261 bool ScriptController::shouldBypassMainWorldContentSecurityPolicy()
263 if (DOMWrapperWorld* world = isolatedWorldForEnteredContext(m_isolate))
264 return world->isolatedWorldHasContentSecurityPolicy();
268 TextPosition ScriptController::eventHandlerPosition() const
270 ScriptableDocumentParser* parser = m_frame->document()->scriptableDocumentParser();
272 return parser->textPosition();
273 return TextPosition::minimumPosition();
276 static inline v8::Local<v8::Context> contextForWorld(ScriptController& scriptController, DOMWrapperWorld* world)
278 return scriptController.windowShell(world)->context();
281 v8::Local<v8::Context> ScriptController::currentWorldContextOrMainWorldContext()
283 if (!isolate()->InContext())
284 return contextForWorld(*this, mainThreadNormalWorld());
286 v8::Handle<v8::Context> context = isolate()->GetEnteredContext();
287 DOMWrapperWorld* isolatedWorld = DOMWrapperWorld::isolatedWorld(context);
289 return contextForWorld(*this, mainThreadNormalWorld());
291 Frame* frame = toFrameIfNotDetached(context);
292 if (m_frame == frame)
293 return v8::Local<v8::Context>::New(m_isolate, context);
295 return contextForWorld(*this, isolatedWorld);
298 v8::Local<v8::Context> ScriptController::mainWorldContext()
300 return contextForWorld(*this, mainThreadNormalWorld());
303 v8::Local<v8::Context> ScriptController::mainWorldContext(Frame* frame)
306 return v8::Local<v8::Context>();
308 return contextForWorld(frame->script(), mainThreadNormalWorld());
311 // Create a V8 object with an interceptor of NPObjectPropertyGetter.
312 void ScriptController::bindToWindowObject(Frame* frame, const String& key, NPObject* object)
314 v8::HandleScope handleScope(m_isolate);
316 v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(frame);
317 if (v8Context.IsEmpty())
320 v8::Context::Scope scope(v8Context);
322 v8::Handle<v8::Object> value = createV8ObjectForNPObject(object, 0, m_isolate);
324 // Attach to the global object.
325 v8::Handle<v8::Object> global = v8Context->Global();
326 global->Set(v8String(m_isolate, key), value);
329 void ScriptController::enableEval()
331 if (!m_windowShell->isContextInitialized())
333 v8::HandleScope handleScope(m_isolate);
334 m_windowShell->context()->AllowCodeGenerationFromStrings(true);
337 void ScriptController::disableEval(const String& errorMessage)
339 if (!m_windowShell->isContextInitialized())
341 v8::HandleScope handleScope(m_isolate);
342 v8::Local<v8::Context> v8Context = m_windowShell->context();
343 v8Context->AllowCodeGenerationFromStrings(false);
344 v8Context->SetErrorMessageForCodeGenerationFromStrings(v8String(m_isolate, errorMessage));
347 PassRefPtr<SharedPersistent<v8::Object> > ScriptController::createPluginWrapper(Widget* widget)
351 if (!widget->isPluginView())
354 NPObject* npObject = toPluginView(widget)->scriptableObject();
358 // Frame Memory Management for NPObjects
359 // -------------------------------------
360 // NPObjects are treated differently than other objects wrapped by JS.
361 // NPObjects can be created either by the browser (e.g. the main
362 // window object) or by the plugin (the main plugin object
363 // for a HTMLEmbedElement). Further, unlike most DOM Objects, the frame
364 // is especially careful to ensure NPObjects terminate at frame teardown because
365 // if a plugin leaks a reference, it could leak its objects (or the browser's objects).
367 // The Frame maintains a list of plugin objects (m_pluginObjects)
368 // which it can use to quickly find the wrapped embed object.
370 // Inside the NPRuntime, we've added a few methods for registering
371 // wrapped NPObjects. The purpose of the registration is because
372 // javascript garbage collection is non-deterministic, yet we need to
373 // be able to tear down the plugin objects immediately. When an object
374 // is registered, javascript can use it. When the object is destroyed,
375 // or when the object's "owning" object is destroyed, the object will
376 // be un-registered, and the javascript engine must not use it.
378 // Inside the javascript engine, the engine can keep a reference to the
379 // NPObject as part of its wrapper. However, before accessing the object
380 // it must consult the _NPN_Registry.
382 v8::Local<v8::Object> wrapper = createV8ObjectForNPObject(npObject, 0, m_isolate);
384 // Track the plugin object. We've been given a reference to the object.
385 m_pluginObjects.set(widget, npObject);
387 return SharedPersistent<v8::Object>::create(wrapper, m_isolate);
390 void ScriptController::cleanupScriptObjectsForPlugin(Widget* nativeHandle)
392 PluginObjectMap::iterator it = m_pluginObjects.find(nativeHandle);
393 if (it == m_pluginObjects.end())
395 _NPN_UnregisterObject(it->value);
396 _NPN_ReleaseObject(it->value);
397 m_pluginObjects.remove(it);
400 V8Extensions& ScriptController::registeredExtensions()
402 DEFINE_STATIC_LOCAL(V8Extensions, extensions, ());
406 void ScriptController::registerExtensionIfNeeded(v8::Extension* extension)
408 const V8Extensions& extensions = registeredExtensions();
409 for (size_t i = 0; i < extensions.size(); ++i) {
410 if (extensions[i] == extension)
413 v8::RegisterExtension(extension);
414 registeredExtensions().append(extension);
417 static NPObject* createNoScriptObject()
423 static NPObject* createScriptObject(Frame* frame, v8::Isolate* isolate)
425 v8::HandleScope handleScope(isolate);
426 v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(frame);
427 if (v8Context.IsEmpty())
428 return createNoScriptObject();
430 v8::Context::Scope scope(v8Context);
431 DOMWindow* window = frame->domWindow();
432 v8::Handle<v8::Value> global = toV8(window, v8::Handle<v8::Object>(), v8Context->GetIsolate());
433 ASSERT(global->IsObject());
435 return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(global), window, isolate);
438 NPObject* ScriptController::windowScriptNPObject()
440 if (m_windowScriptNPObject)
441 return m_windowScriptNPObject;
443 if (canExecuteScripts(NotAboutToExecuteScript)) {
444 // JavaScript is enabled, so there is a JavaScript window object.
445 // Return an NPObject bound to the window object.
446 m_windowScriptNPObject = createScriptObject(m_frame, m_isolate);
447 _NPN_RegisterObject(m_windowScriptNPObject, 0);
449 // JavaScript is not enabled, so we cannot bind the NPObject to the
450 // JavaScript window object. Instead, we create an NPObject of a
451 // different class, one which is not bound to a JavaScript object.
452 m_windowScriptNPObject = createNoScriptObject();
454 return m_windowScriptNPObject;
457 NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin)
459 // Can't create NPObjects when JavaScript is disabled.
460 if (!canExecuteScripts(NotAboutToExecuteScript))
461 return createNoScriptObject();
463 v8::HandleScope handleScope(m_isolate);
464 v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame);
465 if (v8Context.IsEmpty())
466 return createNoScriptObject();
467 v8::Context::Scope scope(v8Context);
469 DOMWindow* window = m_frame->domWindow();
470 v8::Handle<v8::Value> v8plugin = toV8(plugin, v8::Handle<v8::Object>(), v8Context->GetIsolate());
471 if (!v8plugin->IsObject())
472 return createNoScriptObject();
474 return npCreateV8ScriptObject(0, v8::Handle<v8::Object>::Cast(v8plugin), window, v8Context->GetIsolate());
477 void ScriptController::clearWindowShell()
479 double start = currentTime();
480 // V8 binding expects ScriptController::clearWindowShell only be called
481 // when a frame is loading a new page. This creates a new context for the new page.
482 m_windowShell->clearForNavigation();
483 for (IsolatedWorldMap::iterator iter = m_isolatedWorlds.begin(); iter != m_isolatedWorlds.end(); ++iter)
484 iter->value->clearForNavigation();
485 clearScriptObjects();
486 V8GCController::hintForCollectGarbage();
487 blink::Platform::current()->histogramCustomCounts("WebCore.ScriptController.clearWindowShell", (currentTime() - start) * 1000, 0, 10000, 50);
490 void ScriptController::setCaptureCallStackForUncaughtExceptions(bool value)
492 v8::V8::SetCaptureStackTraceForUncaughtExceptions(value, ScriptCallStack::maxCallStackSizeToCapture, stackTraceOptions);
495 void ScriptController::collectIsolatedContexts(Vector<std::pair<ScriptState*, SecurityOrigin*> >& result)
497 v8::HandleScope handleScope(m_isolate);
498 for (IsolatedWorldMap::iterator it = m_isolatedWorlds.begin(); it != m_isolatedWorlds.end(); ++it) {
499 V8WindowShell* isolatedWorldShell = it->value.get();
500 SecurityOrigin* origin = isolatedWorldShell->world()->isolatedWorldSecurityOrigin();
503 v8::Local<v8::Context> v8Context = isolatedWorldShell->context();
504 if (v8Context.IsEmpty())
506 ScriptState* scriptState = ScriptState::forContext(v8Context);
507 result.append(std::pair<ScriptState*, SecurityOrigin*>(scriptState, origin));
511 bool ScriptController::setContextDebugId(int debugId)
514 if (!m_windowShell->isContextInitialized())
516 v8::HandleScope scope(m_isolate);
517 v8::Local<v8::Context> context = m_windowShell->context();
518 return V8PerContextDebugData::setContextDebugData(context, "page", debugId);
521 int ScriptController::contextDebugId(v8::Handle<v8::Context> context)
523 return V8PerContextDebugData::contextDebugId(context);
526 void ScriptController::updateDocument()
528 // For an uninitialized main window shell, do not incur the cost of context initialization during FrameLoader::init().
529 if ((!m_windowShell->isContextInitialized() || !m_windowShell->isGlobalInitialized()) && m_frame->loader().stateMachine()->creatingInitialEmptyDocument())
532 if (!initializeMainWorld())
533 windowShell(mainThreadNormalWorld())->updateDocument();
536 void ScriptController::namedItemAdded(HTMLDocument* doc, const AtomicString& name)
538 windowShell(mainThreadNormalWorld())->namedItemAdded(doc, name);
541 void ScriptController::namedItemRemoved(HTMLDocument* doc, const AtomicString& name)
543 windowShell(mainThreadNormalWorld())->namedItemRemoved(doc, name);
546 bool ScriptController::canExecuteScripts(ReasonForCallingCanExecuteScripts reason)
548 if (m_frame->document() && m_frame->document()->isSandboxed(SandboxScripts)) {
549 // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
550 if (reason == AboutToExecuteScript)
551 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.");
555 if (m_frame->document() && m_frame->document()->isViewSource()) {
556 ASSERT(m_frame->document()->securityOrigin()->isUnique());
560 Settings* settings = m_frame->settings();
561 const bool allowed = m_frame->loader().client()->allowScript(settings && settings->isScriptEnabled());
562 if (!allowed && reason == AboutToExecuteScript)
563 m_frame->loader().client()->didNotAllowScript();
567 bool ScriptController::executeScriptIfJavaScriptURL(const KURL& url)
569 if (!protocolIsJavaScript(url))
573 || !m_frame->document()->contentSecurityPolicy()->allowJavaScriptURLs(m_frame->document()->url(), eventHandlerPosition().m_line))
576 // We need to hold onto the Frame here because executing script can
577 // destroy the frame.
578 RefPtr<Frame> protector(m_frame);
579 RefPtr<Document> ownerDocument(m_frame->document());
581 const int javascriptSchemeLength = sizeof("javascript:") - 1;
583 bool locationChangeBefore = m_frame->navigationScheduler().locationChangePending();
585 String decodedURL = decodeURLEscapeSequences(url.string());
586 ScriptValue result = evaluateScriptInMainWorld(ScriptSourceCode(decodedURL.substring(javascriptSchemeLength)), NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
588 // If executing script caused this frame to be removed from the page, we
589 // don't want to try to replace its document!
590 if (!m_frame->page())
594 if (!result.getString(scriptResult))
597 // We're still in a frame, so there should be a DocumentLoader.
598 ASSERT(m_frame->document()->loader());
600 if (!locationChangeBefore && m_frame->navigationScheduler().locationChangePending())
603 // DocumentWriter::replaceDocument can cause the DocumentLoader to get deref'ed and possible destroyed,
604 // so protect it with a RefPtr.
605 if (RefPtr<DocumentLoader> loader = m_frame->document()->loader()) {
606 UseCounter::count(*m_frame->document(), UseCounter::ReplaceDocumentViaJavaScriptURL);
607 loader->replaceDocument(scriptResult, ownerDocument.get());
612 void ScriptController::executeScriptInMainWorld(const String& script, ExecuteScriptPolicy policy)
614 evaluateScriptInMainWorld(ScriptSourceCode(script), NotSharableCrossOrigin, policy);
617 void ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus)
619 evaluateScriptInMainWorld(sourceCode, corsStatus, DoNotExecuteScriptWhenScriptsDisabled);
622 ScriptValue ScriptController::executeScriptInMainWorldAndReturnValue(const ScriptSourceCode& sourceCode)
624 return evaluateScriptInMainWorld(sourceCode, NotSharableCrossOrigin, DoNotExecuteScriptWhenScriptsDisabled);
627 ScriptValue ScriptController::evaluateScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus, ExecuteScriptPolicy policy)
629 if (policy == DoNotExecuteScriptWhenScriptsDisabled && !canExecuteScripts(AboutToExecuteScript))
630 return ScriptValue();
632 String sourceURL = sourceCode.url();
633 const String* savedSourceURL = m_sourceURL;
634 m_sourceURL = &sourceURL;
636 v8::HandleScope handleScope(m_isolate);
637 v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame);
638 if (v8Context.IsEmpty())
639 return ScriptValue();
641 RefPtr<Frame> protect(m_frame);
642 if (m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument())
643 m_frame->loader().didAccessInitialDocument();
645 OwnPtr<ScriptSourceCode> maybeProcessedSourceCode = InspectorInstrumentation::preprocess(m_frame, sourceCode);
646 const ScriptSourceCode& sourceCodeToCompile = maybeProcessedSourceCode ? *maybeProcessedSourceCode : sourceCode;
648 v8::Local<v8::Value> object = executeScriptAndReturnValue(v8Context, sourceCodeToCompile, corsStatus);
649 m_sourceURL = savedSourceURL;
651 if (object.IsEmpty())
652 return ScriptValue();
654 return ScriptValue(object, m_isolate);
657 void ScriptController::executeScriptInIsolatedWorld(int worldID, const Vector<ScriptSourceCode>& sources, int extensionGroup, Vector<ScriptValue>* results)
661 v8::HandleScope handleScope(m_isolate);
662 v8::Local<v8::Array> v8Results;
664 v8::EscapableHandleScope evaluateHandleScope(m_isolate);
665 RefPtr<DOMWrapperWorld> world = DOMWrapperWorld::ensureIsolatedWorld(worldID, extensionGroup);
666 V8WindowShell* isolatedWorldShell = windowShell(world.get());
668 if (!isolatedWorldShell->isContextInitialized())
671 v8::Local<v8::Context> context = isolatedWorldShell->context();
672 v8::Context::Scope contextScope(context);
673 v8::Local<v8::Array> resultArray = v8::Array::New(m_isolate, sources.size());
675 for (size_t i = 0; i < sources.size(); ++i) {
676 v8::Local<v8::Value> evaluationResult = executeScriptAndReturnValue(context, sources[i]);
677 if (evaluationResult.IsEmpty())
678 evaluationResult = v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate));
679 resultArray->Set(i, evaluationResult);
682 v8Results = evaluateHandleScope.Escape(resultArray);
685 if (results && !v8Results.IsEmpty()) {
686 for (size_t i = 0; i < v8Results->Length(); ++i)
687 results->append(ScriptValue(v8Results->Get(i), m_isolate));
691 } // namespace WebCore