IntersectionObserver* IntersectionObserver::create(const IntersectionObserverInit& observerInit, IntersectionObserverCallback& callback, ExceptionState& exceptionState)
{
    RefPtrWillBeRawPtr<Node> root = observerInit.root();
    if (!root) {
        // TODO(szager): Use Document instead of document element for implicit root. (crbug.com/570538)
        ExecutionContext* context = callback.executionContext();
        ASSERT(context->isDocument());
        Frame* mainFrame = toDocument(context)->frame()->tree().top();
        if (mainFrame && mainFrame->isLocalFrame())
            root = toLocalFrame(mainFrame)->document();
    }
    if (!root) {
        exceptionState.throwDOMException(HierarchyRequestError, "Unable to get root node in main frame to track.");
        return nullptr;
    }

    Vector<Length> rootMargin;
    if (observerInit.hasRootMargin())
        parseRootMargin(observerInit.rootMargin(), rootMargin, exceptionState);
    if (exceptionState.hadException())
        return nullptr;

    Vector<float> thresholds;
    if (observerInit.hasThreshold())
        parseThresholds(observerInit.threshold(), thresholds, exceptionState);
    else
        thresholds.append(0);
    if (exceptionState.hadException())
        return nullptr;

    return new IntersectionObserver(callback, *root, rootMargin, thresholds);
}
v8::MaybeLocal<v8::Value> MainThreadDebugger::memoryInfo(v8::Isolate* isolate, v8::Local<v8::Context> context)
{
    ExecutionContext* executionContext = toExecutionContext(context);
    ASSERT_UNUSED(executionContext, executionContext);
    ASSERT(executionContext->isDocument());
    return toV8(MemoryInfo::create(), context->Global(), isolate);
}
Ejemplo n.º 3
0
static void messageHandlerInMainThread(v8::Local<v8::Message> message,
                                       v8::Local<v8::Value> data) {
  ASSERT(isMainThread());
  v8::Isolate* isolate = v8::Isolate::GetCurrent();

  if (isolate->GetEnteredContext().IsEmpty())
    return;

  // If called during context initialization, there will be no entered context.
  ScriptState* scriptState = ScriptState::current(isolate);
  if (!scriptState->contextIsValid())
    return;

  ExecutionContext* context = scriptState->getExecutionContext();
  std::unique_ptr<SourceLocation> location =
      SourceLocation::fromMessage(isolate, message, context);

  AccessControlStatus accessControlStatus = NotSharableCrossOrigin;
  if (message->IsOpaque())
    accessControlStatus = OpaqueResource;
  else if (message->IsSharedCrossOrigin())
    accessControlStatus = SharableCrossOrigin;

  ErrorEvent* event =
      ErrorEvent::create(toCoreStringWithNullCheck(message->Get()),
                         std::move(location), &scriptState->world());

  String messageForConsole = extractMessageForConsole(isolate, data);
  if (!messageForConsole.isEmpty())
    event->setUnsanitizedMessage("Uncaught " + messageForConsole);

  // This method might be called while we're creating a new context. In this
  // case, we avoid storing the exception object, as we can't create a wrapper
  // during context creation.
  // FIXME: Can we even get here during initialization now that we bail out when
  // GetEntered returns an empty handle?
  if (context->isDocument()) {
    LocalFrame* frame = toDocument(context)->frame();
    if (frame && frame->script().existingWindowProxy(scriptState->world())) {
      V8ErrorHandler::storeExceptionOnErrorEventWrapper(
          scriptState, event, data, scriptState->context()->Global());
    }
  }

  if (scriptState->world().isPrivateScriptIsolatedWorld()) {
    // We allow a private script to dispatch error events even in a
    // EventDispatchForbiddenScope scope.  Without having this ability, it's
    // hard to debug the private script because syntax errors in the private
    // script are not reported to console (the private script just crashes
    // silently).  Allowing error events in private scripts is safe because
    // error events don't propagate to other isolated worlds (which means that
    // the error events won't fire any event listeners in user's scripts).
    EventDispatchForbiddenScope::AllowUserAgentEvents allowUserAgentEvents;
    context->dispatchErrorEvent(event, accessControlStatus);
  } else {
    context->dispatchErrorEvent(event, accessControlStatus);
  }
}
Ejemplo n.º 4
0
void injectInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    v8::Handle<v8::Object> global = scriptState->context()->Global();
    ExecutionContext* executionContext = scriptState->executionContext();
    if (executionContext->isDocument())
        global->Set(v8::String::NewFromUtf8(scriptState->isolate(), Internals::internalsId), toV8(Internals::create(toDocument(executionContext)), global, scriptState->isolate()));
}
static Document* documentFromEventTarget(EventTarget& target)
{
    ExecutionContext* executionContext = target.executionContext();
    if (!executionContext)
        return nullptr;
    if (executionContext->isDocument())
        return toDocument(executionContext);
    if (LocalDOMWindow* executingWindow = executionContext->executingWindow())
        return executingWindow->document();
    return nullptr;
}
static Node* secondArgumentAsNode(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    if (info.Length() > 1) {
        if (Node* node = V8Node::toImplWithTypeCheck(info.GetIsolate(), info[1]))
            return node;
    }
    ExecutionContext* executionContext = toExecutionContext(info.GetIsolate()->GetCurrentContext());
    if (executionContext->isDocument())
        return toDocument(executionContext);
    return nullptr;
}
Ejemplo n.º 7
0
void injectInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    v8::Local<v8::Object> global = scriptState->context()->Global();
    ExecutionContext* executionContext = scriptState->executionContext();
    if (executionContext->isDocument()) {
        v8::Local<v8::Value> internals = toV8(Internals::create(toDocument(executionContext)), global, scriptState->isolate());
        ASSERT(!internals.IsEmpty());
        v8CallOrCrash(global->Set(scriptState->context(), v8AtomicString(scriptState->isolate(), Internals::internalsId), internals));
    }
}
Ejemplo n.º 8
0
int setTimeout(ScriptState* scriptState, EventTarget& eventTarget, const ScriptValue& handler, int timeout, const Vector<ScriptValue>& arguments)
{
    ExecutionContext* executionContext = eventTarget.executionContext();
    if (!isAllowed(scriptState, executionContext, false))
        return 0;
    if (timeout >= 0 && executionContext->isDocument()) {
        // FIXME: Crude hack that attempts to pass idle time to V8. This should
        // be done using the scheduler instead.
        V8GCForContextDispose::instance().notifyIdle();
    }
    OwnPtrWillBeRawPtr<ScheduledAction> action = ScheduledAction::create(scriptState, handler, arguments);
    return DOMTimer::install(executionContext, action.release(), timeout, true);
}
Ejemplo n.º 9
0
void InProcessWorkerObjectProxy::postMessageToPageInspector(
    const String& message) {
  ExecutionContext* context = getExecutionContext();
  if (context->isDocument()) {
    // TODO(hiroshige): consider using getParentFrameTaskRunners() here
    // too.
    toDocument(context)->postInspectorTask(
        BLINK_FROM_HERE,
        createCrossThreadTask(
            &InProcessWorkerMessagingProxy::postMessageToPageInspector,
            m_messagingProxyWeakPtr, message));
  }
}
Ejemplo n.º 10
0
void DatabaseTracker::forEachOpenDatabaseInPage(Page* page, std::unique_ptr<DatabaseCallback> callback)
{
    MutexLocker openDatabaseMapLock(m_openDatabaseMapGuard);
    if (!m_openDatabaseMap)
        return;
    for (auto& originMap : *m_openDatabaseMap) {
        for (auto& nameDatabaseSet : *originMap.value) {
            for (Database* database : *nameDatabaseSet.value) {
                ExecutionContext* context = database->getExecutionContext();
                ASSERT(context->isDocument());
                if (toDocument(context)->frame()->page() == page)
                    (*callback)(database);
            }
        }
    }
}
void V8XMLHttpRequest::constructorCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExecutionContext* context = currentExecutionContext(info.GetIsolate());

    RefPtr<SecurityOrigin> securityOrigin;
    if (context->isDocument()) {
        DOMWrapperWorld& world = DOMWrapperWorld::current(info.GetIsolate());
        if (world.isIsolatedWorld())
            securityOrigin = world.isolatedWorldSecurityOrigin();
    }

    RefPtrWillBeRawPtr<XMLHttpRequest> xmlHttpRequest = XMLHttpRequest::create(context, securityOrigin);

    v8::Handle<v8::Object> wrapper = info.Holder();
    V8DOMWrapper::associateObjectWithWrapper<V8XMLHttpRequest>(xmlHttpRequest.release(), &wrapperTypeInfo, wrapper, info.GetIsolate(), WrapperConfiguration::Dependent);
    info.GetReturnValue().Set(wrapper);
}
Ejemplo n.º 12
0
ScriptPromise USB::requestDevice(ScriptState* scriptState,
                                 const USBDeviceRequestOptions& options) {
  ExecutionContext* executionContext = scriptState->getExecutionContext();
  UseCounter::count(executionContext, UseCounter::UsbRequestDevice);

  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();

  if (!m_chooserService) {
    LocalFrame* frame = executionContext->isDocument()
                            ? toDocument(executionContext)->frame()
                            : nullptr;
    if (!frame) {
      resolver->reject(DOMException::create(NotSupportedError));
      return promise;
    }
    frame->interfaceProvider()->getInterface(mojo::GetProxy(&m_chooserService));
    m_chooserService.set_connection_error_handler(
        convertToBaseCallback(WTF::bind(&USB::onChooserServiceConnectionError,
                                        wrapWeakPersistent(this))));
  }

  String errorMessage;
  if (!executionContext->isSecureContext(errorMessage)) {
    resolver->reject(DOMException::create(SecurityError, errorMessage));
  } else if (!UserGestureIndicator::consumeUserGesture()) {
    resolver->reject(DOMException::create(
        SecurityError,
        "Must be handling a user gesture to show a permission request."));
  } else {
    Vector<usb::DeviceFilterPtr> filters;
    if (options.hasFilters()) {
      filters.reserveCapacity(options.filters().size());
      for (const auto& filter : options.filters())
        filters.append(convertDeviceFilter(filter));
    }
    m_chooserServiceRequests.add(resolver);
    m_chooserService->GetPermission(
        std::move(filters), convertToBaseCallback(WTF::bind(
                                &USB::onGetPermission, wrapPersistent(this),
                                wrapPersistent(resolver))));
  }
  return promise;
}
Ejemplo n.º 13
0
void ElementVisibilityObserver::start() {
  ExecutionContext* context = m_element->getExecutionContext();
  DCHECK(context->isDocument());
  Document& document = toDocument(*context);

  // TODO(zqzhang): IntersectionObserver does not work for RemoteFrame.
  // Remove this early return when it's fixed. See https://crbug.com/615156
  if (isInRemoteFrame(document)) {
    m_element.release();
    return;
  }

  DCHECK(!m_intersectionObserver);
  m_intersectionObserver = IntersectionObserver::create(
      Vector<Length>(), Vector<float>({std::numeric_limits<float>::min()}),
      &document, WTF::bind(&ElementVisibilityObserver::onVisibilityChanged,
                           wrapWeakPersistent(this)));
  DCHECK(m_intersectionObserver);
  m_intersectionObserver->setInitialState(
      IntersectionObserver::InitialState::kAuto);
  m_intersectionObserver->observe(m_element.release());
}
void WorkerObjectProxy::postWorkerConsoleAgentEnabled()
{
    ExecutionContext* context = getExecutionContext();
    if (context->isDocument())
        toDocument(context)->postInspectorTask(BLINK_FROM_HERE, createCrossThreadTask(&WorkerMessagingProxy::postWorkerConsoleAgentEnabled, m_messagingProxy));
}
void WorkerObjectProxy::postMessageToPageInspector(const String& message)
{
    ExecutionContext* context = getExecutionContext();
    if (context->isDocument())
        toDocument(context)->postInspectorTask(BLINK_FROM_HERE, createCrossThreadTask(&WorkerMessagingProxy::postMessageToPageInspector, m_messagingProxy, message));
}