Home | History | Annotate | Download | only in v8
      1 /*
      2  * Copyright (C) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions are
      6  * met:
      7  *
      8  *     * Redistributions of source code must retain the above copyright
      9  * notice, this list of conditions and the following disclaimer.
     10  *     * Redistributions in binary form must reproduce the above
     11  * copyright notice, this list of conditions and the following disclaimer
     12  * in the documentation and/or other materials provided with the
     13  * distribution.
     14  *     * Neither the name of Google Inc. nor the names of its
     15  * contributors may be used to endorse or promote products derived from
     16  * this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 #include "config.h"
     32 #include "bindings/v8/V8AbstractEventListener.h"
     33 
     34 #include "V8Event.h"
     35 #include "V8EventTarget.h"
     36 #include "bindings/v8/V8Binding.h"
     37 #include "bindings/v8/V8EventListenerList.h"
     38 #include "bindings/v8/V8HiddenPropertyName.h"
     39 #include "core/events/BeforeUnloadEvent.h"
     40 #include "core/events/Event.h"
     41 #include "core/events/ThreadLocalEventNames.h"
     42 #include "core/inspector/InspectorCounters.h"
     43 #include "core/workers/WorkerGlobalScope.h"
     44 
     45 namespace WebCore {
     46 
     47 V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, PassRefPtr<DOMWrapperWorld> world, v8::Isolate* isolate)
     48     : EventListener(JSEventListenerType)
     49     , m_isAttribute(isAttribute)
     50     , m_world(world)
     51     , m_isolate(isolate)
     52 {
     53     if (isMainThread())
     54         InspectorCounters::incrementCounter(InspectorCounters::JSEventListenerCounter);
     55 }
     56 
     57 V8AbstractEventListener::~V8AbstractEventListener()
     58 {
     59     if (!m_listener.isEmpty()) {
     60         v8::HandleScope scope(m_isolate);
     61         V8EventListenerList::clearWrapper(m_listener.newLocal(m_isolate), m_isAttribute, m_isolate);
     62     }
     63     if (isMainThread())
     64         InspectorCounters::decrementCounter(InspectorCounters::JSEventListenerCounter);
     65 }
     66 
     67 void V8AbstractEventListener::handleEvent(ExecutionContext* context, Event* event)
     68 {
     69     // Don't reenter V8 if execution was terminated in this instance of V8.
     70     if (context->isJSExecutionForbidden())
     71         return;
     72 
     73     ASSERT(event);
     74 
     75     // The callback function on XMLHttpRequest can clear the event listener and destroys 'this' object. Keep a local reference to it.
     76     // See issue 889829.
     77     RefPtr<V8AbstractEventListener> protect(this);
     78 
     79     v8::HandleScope handleScope(m_isolate);
     80 
     81     v8::Local<v8::Context> v8Context = toV8Context(context, world());
     82     if (v8Context.IsEmpty())
     83         return;
     84 
     85     // Enter the V8 context in which to perform the event handling.
     86     v8::Context::Scope scope(v8Context);
     87 
     88     // Get the V8 wrapper for the event object.
     89     v8::Isolate* isolate = v8Context->GetIsolate();
     90     v8::Handle<v8::Value> jsEvent = toV8(event, v8::Handle<v8::Object>(), isolate);
     91     if (jsEvent.IsEmpty())
     92         return;
     93     invokeEventHandler(context, event, v8::Local<v8::Value>::New(isolate, jsEvent));
     94 }
     95 
     96 void V8AbstractEventListener::setListenerObject(v8::Handle<v8::Object> listener)
     97 {
     98     m_listener.set(m_isolate, listener);
     99     m_listener.setWeak(this, &setWeakCallback);
    100 }
    101 
    102 void V8AbstractEventListener::invokeEventHandler(ExecutionContext* context, Event* event, v8::Local<v8::Value> jsEvent)
    103 {
    104     // If jsEvent is empty, attempt to set it as a hidden value would crash v8.
    105     if (jsEvent.IsEmpty())
    106         return;
    107 
    108     v8::Local<v8::Context> v8Context = toV8Context(context, world());
    109     if (v8Context.IsEmpty())
    110         return;
    111 
    112     // We push the event being processed into the global object, so that it can be exposed by DOMWindow's bindings.
    113     v8::Handle<v8::String> eventSymbol = V8HiddenPropertyName::event(v8Context->GetIsolate());
    114     v8::Local<v8::Value> returnValue;
    115 
    116     {
    117         // Catch exceptions thrown in the event handler so they do not propagate to javascript code that caused the event to fire.
    118         v8::TryCatch tryCatch;
    119         tryCatch.SetVerbose(true);
    120 
    121         // Save the old 'event' property so we can restore it later.
    122         v8::Local<v8::Value> savedEvent = v8Context->Global()->GetHiddenValue(eventSymbol);
    123         tryCatch.Reset();
    124 
    125         // Make the event available in the global object, so DOMWindow can expose it.
    126         v8Context->Global()->SetHiddenValue(eventSymbol, jsEvent);
    127         tryCatch.Reset();
    128 
    129         returnValue = callListenerFunction(context, jsEvent, event);
    130         if (tryCatch.HasCaught())
    131             event->target()->uncaughtExceptionInEventHandler();
    132 
    133         if (!tryCatch.CanContinue()) { // Result of TerminateExecution().
    134             if (context->isWorkerGlobalScope())
    135                 toWorkerGlobalScope(context)->script()->forbidExecution();
    136             return;
    137         }
    138         tryCatch.Reset();
    139 
    140         // Restore the old event. This must be done for all exit paths through this method.
    141         if (savedEvent.IsEmpty())
    142             v8Context->Global()->SetHiddenValue(eventSymbol, v8::Undefined(v8Context->GetIsolate()));
    143         else
    144             v8Context->Global()->SetHiddenValue(eventSymbol, savedEvent);
    145         tryCatch.Reset();
    146     }
    147 
    148     ASSERT(!handleOutOfMemory() || returnValue.IsEmpty());
    149 
    150     if (returnValue.IsEmpty())
    151         return;
    152 
    153     if (!returnValue->IsNull() && !returnValue->IsUndefined() && event->isBeforeUnloadEvent()) {
    154         V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, stringReturnValue, returnValue);
    155         toBeforeUnloadEvent(event)->setReturnValue(stringReturnValue);
    156     }
    157 
    158     if (m_isAttribute && shouldPreventDefault(returnValue))
    159         event->preventDefault();
    160 }
    161 
    162 bool V8AbstractEventListener::shouldPreventDefault(v8::Local<v8::Value> returnValue)
    163 {
    164     // Prevent default action if the return value is false in accord with the spec
    165     // http://www.w3.org/TR/html5/webappapis.html#event-handler-attributes
    166     return returnValue->IsBoolean() && !returnValue->BooleanValue();
    167 }
    168 
    169 v8::Local<v8::Object> V8AbstractEventListener::getReceiverObject(ExecutionContext* context, Event* event)
    170 {
    171     v8::Isolate* isolate = toV8Context(context, world())->GetIsolate();
    172     v8::Local<v8::Object> listener = m_listener.newLocal(isolate);
    173     if (!m_listener.isEmpty() && !listener->IsFunction())
    174         return listener;
    175 
    176     EventTarget* target = event->currentTarget();
    177     v8::Handle<v8::Value> value = toV8(target, v8::Handle<v8::Object>(), isolate);
    178     if (value.IsEmpty())
    179         return v8::Local<v8::Object>();
    180     return v8::Local<v8::Object>::New(isolate, v8::Handle<v8::Object>::Cast(value));
    181 }
    182 
    183 void V8AbstractEventListener::setWeakCallback(const v8::WeakCallbackData<v8::Object, V8AbstractEventListener> &data)
    184 {
    185     data.GetParameter()->m_listener.clear();
    186 }
    187 
    188 } // namespace WebCore
    189