2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * Copyright (C) 2015 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 "InspectorPageAgent.h"
35 #include "CachedCSSStyleSheet.h"
36 #include "CachedFont.h"
37 #include "CachedImage.h"
38 #include "CachedResource.h"
39 #include "CachedResourceLoader.h"
40 #include "CachedScript.h"
42 #include "CookieJar.h"
43 #include "DOMPatchSupport.h"
44 #include "DOMWrapperWorld.h"
46 #include "DocumentLoader.h"
48 #include "FrameLoadRequest.h"
49 #include "FrameLoader.h"
50 #include "FrameSnapshotting.h"
51 #include "FrameView.h"
52 #include "HTMLFrameOwnerElement.h"
53 #include "HTMLNames.h"
54 #include "ImageBuffer.h"
55 #include "InspectorClient.h"
56 #include "InspectorDOMAgent.h"
57 #include "InspectorNetworkAgent.h"
58 #include "InspectorOverlay.h"
59 #include "InstrumentingAgents.h"
60 #include "MIMETypeRegistry.h"
61 #include "MainFrame.h"
62 #include "MemoryCache.h"
64 #include "RenderObject.h"
65 #include "ScriptController.h"
66 #include "SecurityOrigin.h"
68 #include "StyleScope.h"
69 #include "TextEncoding.h"
70 #include "TextResourceDecoder.h"
71 #include "UserGestureIndicator.h"
72 #include <inspector/ContentSearchUtilities.h>
73 #include <inspector/IdentifiersFactory.h>
74 #include <inspector/InspectorValues.h>
75 #include <wtf/ListHashSet.h>
76 #include <wtf/Stopwatch.h>
77 #include <wtf/text/Base64.h>
78 #include <wtf/text/StringBuilder.h>
79 #include <yarr/RegularExpression.h>
81 #if ENABLE(WEB_ARCHIVE) && USE(CF)
82 #include "LegacyWebArchive.h"
85 using namespace Inspector;
89 static bool decodeBuffer(const char* buffer, unsigned size, const String& textEncodingName, String* result)
92 TextEncoding encoding(textEncodingName);
93 if (!encoding.isValid())
94 encoding = WindowsLatin1Encoding();
95 *result = encoding.decode(buffer, size);
101 static bool prepareCachedResourceBuffer(CachedResource* cachedResource, bool* hasZeroSize)
103 *hasZeroSize = false;
107 // Zero-sized resources don't have data at all -- so fake the empty buffer, instead of indicating error by returning 0.
108 if (!cachedResource->encodedSize()) {
116 static bool hasTextContent(CachedResource* cachedResource)
118 InspectorPageAgent::ResourceType type = InspectorPageAgent::cachedResourceType(*cachedResource);
119 return type == InspectorPageAgent::DocumentResource
120 || type == InspectorPageAgent::StylesheetResource
121 || type == InspectorPageAgent::ScriptResource
122 || type == InspectorPageAgent::XHRResource;
125 static RefPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
127 RefPtr<TextResourceDecoder> decoder;
128 if (!textEncodingName.isEmpty())
129 decoder = TextResourceDecoder::create("text/plain", textEncodingName);
130 else if (MIMETypeRegistry::isXMLMIMEType(mimeType)) {
131 decoder = TextResourceDecoder::create("application/xml");
132 decoder->useLenientXMLDecoding();
133 } else if (equalLettersIgnoringASCIICase(mimeType, "text/html"))
134 decoder = TextResourceDecoder::create("text/html", "UTF-8");
136 decoder = TextResourceDecoder::create("text/plain", "UTF-8");
140 bool InspectorPageAgent::cachedResourceContent(CachedResource* cachedResource, String* result, bool* base64Encoded)
142 // FIXME: result should be a String& and base64Encoded should be a bool&.
144 bool prepared = prepareCachedResourceBuffer(cachedResource, &hasZeroSize);
148 *base64Encoded = !hasTextContent(cachedResource);
149 if (*base64Encoded) {
154 if (auto* buffer = cachedResource->resourceBuffer()) {
155 *result = base64Encode(buffer->data(), buffer->size());
162 *result = emptyString();
166 if (cachedResource) {
167 switch (cachedResource->type()) {
168 case CachedResource::CSSStyleSheet:
169 // This can return a null String if the MIME type is invalid.
170 *result = downcast<CachedCSSStyleSheet>(*cachedResource).sheetText();
171 return !result->isNull();
172 case CachedResource::Script:
173 *result = downcast<CachedScript>(*cachedResource).script().toString();
175 case CachedResource::MediaResource:
176 case CachedResource::RawResource: {
177 auto* buffer = cachedResource->resourceBuffer();
180 RefPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
181 // We show content for raw resources only for certain mime types (text, html and xml). Otherwise decoder will be null.
184 *result = decoder->decodeAndFlush(buffer->data(), buffer->size());
188 auto* buffer = cachedResource->resourceBuffer();
189 return decodeBuffer(buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0, cachedResource->encoding(), result);
195 bool InspectorPageAgent::mainResourceContent(Frame* frame, bool withBase64Encode, String* result)
197 RefPtr<SharedBuffer> buffer = frame->loader().documentLoader()->mainResourceData();
200 return InspectorPageAgent::dataContent(buffer->data(), buffer->size(), frame->document()->encoding(), withBase64Encode, result);
204 bool InspectorPageAgent::sharedBufferContent(RefPtr<SharedBuffer>&& buffer, const String& textEncodingName, bool withBase64Encode, String* result)
206 return dataContent(buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0, textEncodingName, withBase64Encode, result);
209 bool InspectorPageAgent::dataContent(const char* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result)
211 if (withBase64Encode) {
212 *result = base64Encode(data, size);
216 return decodeBuffer(data, size, textEncodingName, result);
220 void InspectorPageAgent::resourceContent(ErrorString& errorString, Frame* frame, const URL& url, String* result, bool* base64Encoded)
222 DocumentLoader* loader = assertDocumentLoader(errorString, frame);
226 RefPtr<SharedBuffer> buffer;
227 bool success = false;
228 if (equalIgnoringFragmentIdentifier(url, loader->url())) {
229 *base64Encoded = false;
230 success = mainResourceContent(frame, *base64Encoded, result);
234 success = cachedResourceContent(cachedResource(frame, url), result, base64Encoded);
237 errorString = ASCIILiteral("No resource with given URL found");
241 String InspectorPageAgent::sourceMapURLForResource(CachedResource* cachedResource)
243 static NeverDestroyed<String> sourceMapHTTPHeader(ASCIILiteral("SourceMap"));
244 static NeverDestroyed<String> sourceMapHTTPHeaderDeprecated(ASCIILiteral("X-SourceMap"));
249 // Scripts are handled in a separate path.
250 if (cachedResource->type() != CachedResource::CSSStyleSheet)
253 String sourceMapHeader = cachedResource->response().httpHeaderField(sourceMapHTTPHeader);
254 if (!sourceMapHeader.isEmpty())
255 return sourceMapHeader;
257 sourceMapHeader = cachedResource->response().httpHeaderField(sourceMapHTTPHeaderDeprecated);
258 if (!sourceMapHeader.isEmpty())
259 return sourceMapHeader;
263 if (InspectorPageAgent::cachedResourceContent(cachedResource, &content, &base64Encoded) && !base64Encoded)
264 return ContentSearchUtilities::findStylesheetSourceMapURL(content);
269 CachedResource* InspectorPageAgent::cachedResource(Frame* frame, const URL& url)
274 CachedResource* cachedResource = frame->document()->cachedResourceLoader().cachedResource(MemoryCache::removeFragmentIdentifierIfNeeded(url));
275 if (!cachedResource) {
276 ResourceRequest request(url);
277 #if ENABLE(CACHE_PARTITIONING)
278 request.setDomainForCachePartition(frame->document()->topOrigin()->domainForCachePartition());
280 cachedResource = MemoryCache::singleton().resourceForRequest(request, frame->page()->sessionID());
283 return cachedResource;
286 Inspector::Protocol::Page::ResourceType InspectorPageAgent::resourceTypeJson(InspectorPageAgent::ResourceType resourceType)
288 switch (resourceType) {
289 case DocumentResource:
290 return Inspector::Protocol::Page::ResourceType::Document;
292 return Inspector::Protocol::Page::ResourceType::Image;
294 return Inspector::Protocol::Page::ResourceType::Font;
295 case StylesheetResource:
296 return Inspector::Protocol::Page::ResourceType::Stylesheet;
298 return Inspector::Protocol::Page::ResourceType::Script;
300 return Inspector::Protocol::Page::ResourceType::XHR;
301 case WebSocketResource:
302 return Inspector::Protocol::Page::ResourceType::WebSocket;
304 return Inspector::Protocol::Page::ResourceType::Other;
306 return Inspector::Protocol::Page::ResourceType::Other;
309 InspectorPageAgent::ResourceType InspectorPageAgent::cachedResourceType(const CachedResource& cachedResource)
311 switch (cachedResource.type()) {
312 case CachedResource::ImageResource:
313 return InspectorPageAgent::ImageResource;
314 #if ENABLE(SVG_FONTS)
315 case CachedResource::SVGFontResource:
317 case CachedResource::FontResource:
318 return InspectorPageAgent::FontResource;
319 case CachedResource::CSSStyleSheet:
322 case CachedResource::XSLStyleSheet:
324 return InspectorPageAgent::StylesheetResource;
325 case CachedResource::Script:
326 return InspectorPageAgent::ScriptResource;
327 case CachedResource::MediaResource:
328 case CachedResource::RawResource:
329 return InspectorPageAgent::XHRResource;
330 case CachedResource::MainResource:
331 return InspectorPageAgent::DocumentResource;
335 return InspectorPageAgent::OtherResource;
338 Inspector::Protocol::Page::ResourceType InspectorPageAgent::cachedResourceTypeJson(const CachedResource& cachedResource)
340 return resourceTypeJson(cachedResourceType(cachedResource));
343 InspectorPageAgent::InspectorPageAgent(PageAgentContext& context, InspectorClient* client, InspectorOverlay* overlay)
344 : InspectorAgentBase(ASCIILiteral("Page"), context)
345 , m_frontendDispatcher(std::make_unique<Inspector::PageFrontendDispatcher>(context.frontendRouter))
346 , m_backendDispatcher(Inspector::PageBackendDispatcher::create(context.backendDispatcher, this))
347 , m_page(context.inspectedPage)
353 void InspectorPageAgent::didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*)
357 void InspectorPageAgent::willDestroyFrontendAndBackend(Inspector::DisconnectReason)
363 double InspectorPageAgent::timestamp()
365 return m_environment.executionStopwatch()->elapsedTime();
368 void InspectorPageAgent::enable(ErrorString&)
371 m_instrumentingAgents.setInspectorPageAgent(this);
373 auto stopwatch = m_environment.executionStopwatch();
377 m_originalScriptExecutionDisabled = !mainFrame().settings().isScriptEnabled();
380 void InspectorPageAgent::disable(ErrorString&)
383 m_scriptsToEvaluateOnLoad = nullptr;
384 m_instrumentingAgents.setInspectorPageAgent(nullptr);
387 setScriptExecutionDisabled(unused, m_originalScriptExecutionDisabled);
388 setShowPaintRects(unused, false);
389 setEmulatedMedia(unused, emptyString());
392 void InspectorPageAgent::addScriptToEvaluateOnLoad(ErrorString&, const String& source, String* identifier)
394 if (!m_scriptsToEvaluateOnLoad)
395 m_scriptsToEvaluateOnLoad = InspectorObject::create();
397 // Assure we don't override existing ids -- m_lastScriptIdentifier could get out of sync WRT actual
398 // scripts once we restored the scripts from the cookie during navigation.
400 *identifier = String::number(++m_lastScriptIdentifier);
401 } while (m_scriptsToEvaluateOnLoad->find(*identifier) != m_scriptsToEvaluateOnLoad->end());
403 m_scriptsToEvaluateOnLoad->setString(*identifier, source);
406 void InspectorPageAgent::removeScriptToEvaluateOnLoad(ErrorString& error, const String& identifier)
408 if (!m_scriptsToEvaluateOnLoad || m_scriptsToEvaluateOnLoad->find(identifier) == m_scriptsToEvaluateOnLoad->end()) {
409 error = ASCIILiteral("Script not found");
413 m_scriptsToEvaluateOnLoad->remove(identifier);
416 void InspectorPageAgent::reload(ErrorString&, const bool* const optionalIgnoreCache, const String* optionalScriptToEvaluateOnLoad)
418 m_pendingScriptToEvaluateOnLoadOnce = optionalScriptToEvaluateOnLoad ? *optionalScriptToEvaluateOnLoad : emptyString();
419 m_page.mainFrame().loader().reload(optionalIgnoreCache ? *optionalIgnoreCache : false);
422 void InspectorPageAgent::navigate(ErrorString&, const String& url)
424 UserGestureIndicator indicator(ProcessingUserGesture);
425 Frame& frame = m_page.mainFrame();
427 ResourceRequest resourceRequest(frame.document()->completeURL(url));
428 FrameLoadRequest frameRequest(frame.document()->securityOrigin(), resourceRequest, "_self", LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, ShouldReplaceDocumentIfJavaScriptURL::ReplaceDocumentIfJavaScriptURL, ShouldOpenExternalURLsPolicy::ShouldNotAllow);
429 frame.loader().changeLocation(frameRequest);
432 static Ref<Inspector::Protocol::Page::Cookie> buildObjectForCookie(const Cookie& cookie)
434 return Inspector::Protocol::Page::Cookie::create()
435 .setName(cookie.name)
436 .setValue(cookie.value)
437 .setDomain(cookie.domain)
438 .setPath(cookie.path)
439 .setExpires(cookie.expires)
440 .setSize((cookie.name.length() + cookie.value.length()))
441 .setHttpOnly(cookie.httpOnly)
442 .setSecure(cookie.secure)
443 .setSession(cookie.session)
447 static Ref<Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>> buildArrayForCookies(ListHashSet<Cookie>& cookiesList)
449 auto cookies = Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>::create();
451 for (const auto& cookie : cookiesList)
452 cookies->addItem(buildObjectForCookie(cookie));
457 static Vector<CachedResource*> cachedResourcesForFrame(Frame* frame)
459 Vector<CachedResource*> result;
461 for (auto& cachedResourceHandle : frame->document()->cachedResourceLoader().allCachedResources().values()) {
462 auto* cachedResource = cachedResourceHandle.get();
463 if (cachedResource->resourceRequest().hiddenFromInspector())
466 switch (cachedResource->type()) {
467 case CachedResource::ImageResource:
468 // Skip images that were not auto loaded (images disabled in the user agent).
469 #if ENABLE(SVG_FONTS)
470 case CachedResource::SVGFontResource:
472 case CachedResource::FontResource:
473 // Skip fonts that were referenced in CSS but never used/downloaded.
474 if (cachedResource->stillNeedsLoad())
478 // All other CachedResource types download immediately.
482 result.append(cachedResource);
488 static Vector<URL> allResourcesURLsForFrame(Frame* frame)
492 result.append(frame->loader().documentLoader()->url());
494 for (auto* cachedResource : cachedResourcesForFrame(frame))
495 result.append(cachedResource->url());
500 void InspectorPageAgent::getCookies(ErrorString&, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>>& cookies)
502 // If we can get raw cookies.
503 ListHashSet<Cookie> rawCookiesList;
505 // If we can't get raw cookies - fall back to String representation
506 StringBuilder stringCookiesList;
508 // Return value to getRawCookies should be the same for every call because
509 // the return value is platform/network backend specific, and the call will
510 // always return the same true/false value.
511 bool rawCookiesImplemented = false;
513 for (Frame* frame = &mainFrame(); frame; frame = frame->tree().traverseNext()) {
514 Document* document = frame->document();
518 for (auto& url : allResourcesURLsForFrame(frame)) {
519 Vector<Cookie> docCookiesList;
520 rawCookiesImplemented = getRawCookies(*document, URL(ParsedURLString, url), docCookiesList);
522 if (!rawCookiesImplemented) {
523 // FIXME: We need duplication checking for the String representation of cookies.
524 // Exceptions are thrown by cookie() in sandboxed frames. That won't happen here
525 // because "document" is the document of the main frame of the page.
526 stringCookiesList.append(document->cookie().releaseReturnValue());
528 for (auto& cookie : docCookiesList) {
529 if (!rawCookiesList.contains(cookie))
530 rawCookiesList.add(cookie);
536 // FIXME: Do not return empty string/empty array. Make returns optional instead. https://bugs.webkit.org/show_bug.cgi?id=80855
537 if (rawCookiesImplemented)
538 cookies = buildArrayForCookies(rawCookiesList);
540 cookies = Inspector::Protocol::Array<Inspector::Protocol::Page::Cookie>::create();
543 void InspectorPageAgent::deleteCookie(ErrorString&, const String& cookieName, const String& url)
545 URL parsedURL(ParsedURLString, url);
546 for (Frame* frame = &m_page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
547 if (auto* document = frame->document())
548 WebCore::deleteCookie(*document, parsedURL, cookieName);
552 void InspectorPageAgent::getResourceTree(ErrorString&, RefPtr<Inspector::Protocol::Page::FrameResourceTree>& object)
554 object = buildObjectForFrameTree(&m_page.mainFrame());
557 void InspectorPageAgent::getResourceContent(ErrorString& errorString, const String& frameId, const String& url, String* content, bool* base64Encoded)
559 Frame* frame = assertFrame(errorString, frameId);
563 resourceContent(errorString, frame, URL(ParsedURLString, url), content, base64Encoded);
566 static bool textContentForCachedResource(CachedResource* cachedResource, String* result)
568 if (hasTextContent(cachedResource)) {
571 if (InspectorPageAgent::cachedResourceContent(cachedResource, result, &base64Encoded)) {
572 ASSERT(!base64Encoded);
579 void InspectorPageAgent::searchInResource(ErrorString& errorString, const String& frameId, const String& url, const String& query, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, const String* optionalRequestId, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>>& results)
581 results = Inspector::Protocol::Array<Inspector::Protocol::GenericTypes::SearchMatch>::create();
583 bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
584 bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
586 if (optionalRequestId) {
587 if (InspectorNetworkAgent* networkAgent = m_instrumentingAgents.inspectorNetworkAgent()) {
588 networkAgent->searchInRequest(errorString, *optionalRequestId, query, caseSensitive, isRegex, results);
593 Frame* frame = assertFrame(errorString, frameId);
597 DocumentLoader* loader = assertDocumentLoader(errorString, frame);
601 URL kurl(ParsedURLString, url);
604 bool success = false;
605 if (equalIgnoringFragmentIdentifier(kurl, loader->url()))
606 success = mainResourceContent(frame, false, &content);
609 CachedResource* resource = cachedResource(frame, kurl);
611 success = textContentForCachedResource(resource, &content);
617 results = ContentSearchUtilities::searchInTextByLines(content, query, caseSensitive, isRegex);
620 static Ref<Inspector::Protocol::Page::SearchResult> buildObjectForSearchResult(const String& frameId, const String& url, int matchesCount)
622 return Inspector::Protocol::Page::SearchResult::create()
625 .setMatchesCount(matchesCount)
629 void InspectorPageAgent::searchInResources(ErrorString&, const String& text, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::SearchResult>>& result)
631 result = Inspector::Protocol::Array<Inspector::Protocol::Page::SearchResult>::create();
633 bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
634 bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
635 JSC::Yarr::RegularExpression regex = ContentSearchUtilities::createSearchRegex(text, caseSensitive, isRegex);
637 for (Frame* frame = &m_page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
640 for (auto* cachedResource : cachedResourcesForFrame(frame)) {
641 if (textContentForCachedResource(cachedResource, &content)) {
642 int matchesCount = ContentSearchUtilities::countRegularExpressionMatches(regex, content);
644 result->addItem(buildObjectForSearchResult(frameId(frame), cachedResource->url(), matchesCount));
648 if (mainResourceContent(frame, false, &content)) {
649 int matchesCount = ContentSearchUtilities::countRegularExpressionMatches(regex, content);
651 result->addItem(buildObjectForSearchResult(frameId(frame), frame->document()->url(), matchesCount));
655 if (InspectorNetworkAgent* networkAgent = m_instrumentingAgents.inspectorNetworkAgent())
656 networkAgent->searchOtherRequests(regex, result);
659 void InspectorPageAgent::setDocumentContent(ErrorString& errorString, const String& frameId, const String& html)
661 Frame* frame = assertFrame(errorString, frameId);
665 Document* document = frame->document();
667 errorString = ASCIILiteral("No Document instance to set HTML for");
670 DOMPatchSupport::patchDocument(*document, html);
673 void InspectorPageAgent::setShowPaintRects(ErrorString&, bool show)
675 m_showPaintRects = show;
676 m_client->setShowPaintRects(show);
678 if (m_client->overridesShowPaintRects())
681 m_overlay->setShowingPaintRects(show);
684 void InspectorPageAgent::getScriptExecutionStatus(ErrorString&, Inspector::PageBackendDispatcherHandler::Result* status)
686 bool disabledByScriptController = false;
687 bool disabledInSettings = false;
688 disabledByScriptController = mainFrame().script().canExecuteScripts(NotAboutToExecuteScript);
689 disabledInSettings = !mainFrame().settings().isScriptEnabled();
691 if (!disabledByScriptController) {
692 *status = Inspector::PageBackendDispatcherHandler::Result::Allowed;
696 if (disabledInSettings)
697 *status = Inspector::PageBackendDispatcherHandler::Result::Disabled;
699 *status = Inspector::PageBackendDispatcherHandler::Result::Forbidden;
702 void InspectorPageAgent::setScriptExecutionDisabled(ErrorString&, bool value)
704 m_ignoreScriptsEnabledNotification = true;
705 mainFrame().settings().setScriptEnabled(!value);
706 m_ignoreScriptsEnabledNotification = false;
709 void InspectorPageAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld& world)
711 if (&world != &mainThreadNormalWorld())
714 if (m_scriptsToEvaluateOnLoad) {
715 for (auto& keyValuePair : *m_scriptsToEvaluateOnLoad) {
717 if (keyValuePair.value->asString(scriptText))
718 frame->script().executeScript(scriptText);
722 if (!m_scriptToEvaluateOnLoadOnce.isEmpty())
723 frame->script().executeScript(m_scriptToEvaluateOnLoadOnce);
726 void InspectorPageAgent::domContentEventFired()
728 m_isFirstLayoutAfterOnLoad = true;
729 m_frontendDispatcher->domContentEventFired(timestamp());
732 void InspectorPageAgent::loadEventFired()
734 m_frontendDispatcher->loadEventFired(timestamp());
737 void InspectorPageAgent::frameNavigated(Frame& frame)
739 if (frame.isMainFrame()) {
740 m_scriptToEvaluateOnLoadOnce = m_pendingScriptToEvaluateOnLoadOnce;
741 m_pendingScriptToEvaluateOnLoadOnce = String();
743 m_frontendDispatcher->frameNavigated(buildObjectForFrame(&frame));
746 void InspectorPageAgent::frameDetached(Frame& frame)
748 HashMap<Frame*, String>::iterator iterator = m_frameToIdentifier.find(&frame);
749 if (iterator != m_frameToIdentifier.end()) {
750 m_frontendDispatcher->frameDetached(iterator->value);
751 m_identifierToFrame.remove(iterator->value);
752 m_frameToIdentifier.remove(iterator);
756 MainFrame& InspectorPageAgent::mainFrame()
758 return m_page.mainFrame();
761 Frame* InspectorPageAgent::frameForId(const String& frameId)
763 return frameId.isEmpty() ? nullptr : m_identifierToFrame.get(frameId);
766 String InspectorPageAgent::frameId(Frame* frame)
769 return emptyString();
770 String identifier = m_frameToIdentifier.get(frame);
771 if (identifier.isNull()) {
772 identifier = IdentifiersFactory::createIdentifier();
773 m_frameToIdentifier.set(frame, identifier);
774 m_identifierToFrame.set(identifier, frame);
779 bool InspectorPageAgent::hasIdForFrame(Frame* frame) const
781 return frame && m_frameToIdentifier.contains(frame);
784 String InspectorPageAgent::loaderId(DocumentLoader* loader)
787 return emptyString();
788 String identifier = m_loaderToIdentifier.get(loader);
789 if (identifier.isNull()) {
790 identifier = IdentifiersFactory::createIdentifier();
791 m_loaderToIdentifier.set(loader, identifier);
796 Frame* InspectorPageAgent::findFrameWithSecurityOrigin(const String& originRawString)
798 for (Frame* frame = &m_page.mainFrame(); frame; frame = frame->tree().traverseNext()) {
799 RefPtr<SecurityOrigin> documentOrigin = frame->document()->securityOrigin();
800 if (documentOrigin->toRawString() == originRawString)
806 Frame* InspectorPageAgent::assertFrame(ErrorString& errorString, const String& frameId)
808 Frame* frame = frameForId(frameId);
810 errorString = ASCIILiteral("No frame for given id found");
815 DocumentLoader* InspectorPageAgent::assertDocumentLoader(ErrorString& errorString, Frame* frame)
817 FrameLoader& frameLoader = frame->loader();
818 DocumentLoader* documentLoader = frameLoader.documentLoader();
820 errorString = ASCIILiteral("No documentLoader for given frame found");
821 return documentLoader;
824 void InspectorPageAgent::loaderDetachedFromFrame(DocumentLoader& loader)
826 m_loaderToIdentifier.remove(&loader);
829 void InspectorPageAgent::frameStartedLoading(Frame& frame)
831 m_frontendDispatcher->frameStartedLoading(frameId(&frame));
834 void InspectorPageAgent::frameStoppedLoading(Frame& frame)
836 m_frontendDispatcher->frameStoppedLoading(frameId(&frame));
839 void InspectorPageAgent::frameScheduledNavigation(Frame& frame, double delay)
841 m_frontendDispatcher->frameScheduledNavigation(frameId(&frame), delay);
844 void InspectorPageAgent::frameClearedScheduledNavigation(Frame& frame)
846 m_frontendDispatcher->frameClearedScheduledNavigation(frameId(&frame));
849 void InspectorPageAgent::willRunJavaScriptDialog(const String& message)
851 m_frontendDispatcher->javascriptDialogOpening(message);
854 void InspectorPageAgent::didRunJavaScriptDialog()
856 m_frontendDispatcher->javascriptDialogClosed();
859 void InspectorPageAgent::didPaint(RenderObject& renderer, const LayoutRect& rect)
861 if (!m_enabled || !m_showPaintRects)
864 LayoutRect absoluteRect = LayoutRect(renderer.localToAbsoluteQuad(FloatRect(rect)).boundingBox());
865 FrameView* view = renderer.document().view();
867 LayoutRect rootRect = absoluteRect;
868 if (!view->frame().isMainFrame()) {
869 IntRect rootViewRect = view->contentsToRootView(snappedIntRect(absoluteRect));
870 rootRect = view->frame().mainFrame().view()->rootViewToContents(rootViewRect);
873 if (m_client->overridesShowPaintRects()) {
874 m_client->showPaintRect(rootRect);
878 m_overlay->showPaintRect(rootRect);
881 void InspectorPageAgent::didLayout()
883 bool isFirstLayout = m_isFirstLayoutAfterOnLoad;
885 m_isFirstLayoutAfterOnLoad = false;
893 void InspectorPageAgent::didScroll()
899 void InspectorPageAgent::didRecalculateStyle()
905 void InspectorPageAgent::scriptsEnabled(bool isEnabled)
907 if (m_ignoreScriptsEnabledNotification)
910 m_frontendDispatcher->scriptsEnabled(isEnabled);
913 Ref<Inspector::Protocol::Page::Frame> InspectorPageAgent::buildObjectForFrame(Frame* frame)
915 ASSERT_ARG(frame, frame);
917 auto frameObject = Inspector::Protocol::Page::Frame::create()
918 .setId(frameId(frame))
919 .setLoaderId(loaderId(frame->loader().documentLoader()))
920 .setUrl(frame->document()->url().string())
921 .setMimeType(frame->loader().documentLoader()->responseMIMEType())
922 .setSecurityOrigin(frame->document()->securityOrigin()->toRawString())
924 if (frame->tree().parent())
925 frameObject->setParentId(frameId(frame->tree().parent()));
926 if (frame->ownerElement()) {
927 String name = frame->ownerElement()->getNameAttribute();
929 name = frame->ownerElement()->attributeWithoutSynchronization(HTMLNames::idAttr);
930 frameObject->setName(name);
936 Ref<Inspector::Protocol::Page::FrameResourceTree> InspectorPageAgent::buildObjectForFrameTree(Frame* frame)
938 ASSERT_ARG(frame, frame);
940 Ref<Inspector::Protocol::Page::Frame> frameObject = buildObjectForFrame(frame);
941 auto subresources = Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResource>::create();
942 auto result = Inspector::Protocol::Page::FrameResourceTree::create()
943 .setFrame(WTFMove(frameObject))
944 .setResources(subresources.copyRef())
947 for (auto* cachedResource : cachedResourcesForFrame(frame)) {
948 auto resourceObject = Inspector::Protocol::Page::FrameResource::create()
949 .setUrl(cachedResource->url())
950 .setType(cachedResourceTypeJson(*cachedResource))
951 .setMimeType(cachedResource->response().mimeType())
953 if (cachedResource->wasCanceled())
954 resourceObject->setCanceled(true);
955 else if (cachedResource->status() == CachedResource::LoadError)
956 resourceObject->setFailed(true);
957 String sourceMappingURL = InspectorPageAgent::sourceMapURLForResource(cachedResource);
958 if (!sourceMappingURL.isEmpty())
959 resourceObject->setSourceMapURL(sourceMappingURL);
960 String targetId = cachedResource->resourceRequest().initiatorIdentifier();
961 if (!targetId.isEmpty())
962 resourceObject->setTargetId(targetId);
963 subresources->addItem(WTFMove(resourceObject));
966 RefPtr<Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResourceTree>> childrenArray;
967 for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
968 if (!childrenArray) {
969 childrenArray = Inspector::Protocol::Array<Inspector::Protocol::Page::FrameResourceTree>::create();
970 result->setChildFrames(childrenArray);
972 childrenArray->addItem(buildObjectForFrameTree(child));
977 void InspectorPageAgent::setEmulatedMedia(ErrorString&, const String& media)
979 if (media == m_emulatedMedia)
982 m_emulatedMedia = media;
983 Document* document = m_page.mainFrame().document();
985 document->styleScope().didChangeStyleSheetEnvironment();
986 document->updateLayout();
990 void InspectorPageAgent::applyEmulatedMedia(String& media)
992 if (!m_emulatedMedia.isEmpty())
993 media = m_emulatedMedia;
996 void InspectorPageAgent::getCompositingBordersVisible(ErrorString&, bool* outParam)
998 *outParam = m_page.settings().showDebugBorders() || m_page.settings().showRepaintCounter();
1001 void InspectorPageAgent::setCompositingBordersVisible(ErrorString&, bool visible)
1003 m_page.settings().setShowDebugBorders(visible);
1004 m_page.settings().setShowRepaintCounter(visible);
1007 void InspectorPageAgent::snapshotNode(ErrorString& errorString, int nodeId, String* outDataURL)
1009 Frame& frame = mainFrame();
1011 InspectorDOMAgent* domAgent = m_instrumentingAgents.inspectorDOMAgent();
1013 Node* node = domAgent->assertNode(errorString, nodeId);
1017 std::unique_ptr<ImageBuffer> snapshot = WebCore::snapshotNode(frame, *node);
1019 errorString = ASCIILiteral("Could not capture snapshot");
1023 *outDataURL = snapshot->toDataURL(ASCIILiteral("image/png"));
1026 void InspectorPageAgent::snapshotRect(ErrorString& errorString, int x, int y, int width, int height, const String& coordinateSystem, String* outDataURL)
1028 Frame& frame = mainFrame();
1030 SnapshotOptions options = SnapshotOptionsNone;
1031 if (coordinateSystem == "Viewport")
1032 options |= SnapshotOptionsInViewCoordinates;
1034 IntRect rectangle(x, y, width, height);
1035 std::unique_ptr<ImageBuffer> snapshot = snapshotFrameRect(frame, rectangle, options);
1038 errorString = ASCIILiteral("Could not capture snapshot");
1042 *outDataURL = snapshot->toDataURL(ASCIILiteral("image/png"));
1045 void InspectorPageAgent::handleJavaScriptDialog(ErrorString& errorString, bool accept, const String* promptText)
1047 if (!m_client->handleJavaScriptDialog(accept, promptText))
1048 errorString = ASCIILiteral("Could not handle JavaScript dialog");
1051 void InspectorPageAgent::archive(ErrorString& errorString, String* data)
1053 #if ENABLE(WEB_ARCHIVE) && USE(CF)
1054 Frame& frame = mainFrame();
1055 RefPtr<LegacyWebArchive> archive = LegacyWebArchive::create(frame);
1057 errorString = ASCIILiteral("Could not create web archive for main frame");
1061 RetainPtr<CFDataRef> buffer = archive->rawDataRepresentation();
1062 *data = base64Encode(CFDataGetBytePtr(buffer.get()), CFDataGetLength(buffer.get()));
1065 errorString = ASCIILiteral("No support for creating archives");
1069 } // namespace WebCore