blob: 29929bcf7e494835f9fc31613d9fb191abd1e8a6 [file] [edit]
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/*
* Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009 Anthony Ricaud <rik@webkit.org>
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import '../../ui/components/adorners/adorners.js';
import '../../ui/kit/kit.js';
import '../../ui/legacy/legacy.js';
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as TextUtils from '../../core/text_utils/text_utils.js';
import * as Protocol from '../../generated/protocol.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as HAR from '../../models/har/har.js';
import * as Logs from '../../models/logs/logs.js';
import * as NetworkTimeCalculator from '../../models/network_time_calculator/network_time_calculator.js';
import * as Persistence from '../../models/persistence/persistence.js';
import * as Workspace from '../../models/workspace/workspace.js';
import * as NetworkForward from '../../panels/network/forward/forward.js';
import * as Sources from '../../panels/sources/sources.js';
import * as Buttons from '../../ui/components/buttons/buttons.js';
import * as RenderCoordinator from '../../ui/components/render_coordinator/render_coordinator.js';
import * as DataGrid from '../../ui/legacy/components/data_grid/data_grid.js';
import dataGridAiButtonStyles from '../../ui/legacy/components/data_grid/dataGridAiButton.css.js';
import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js';
import * as Components from '../../ui/legacy/components/utils/utils.js';
import * as UI from '../../ui/legacy/legacy.js';
import {Directives, html, nothing, render} from '../../ui/lit/lit.js';
import * as Settings from '../../ui/settings/settings.js';
import * as VisualLogging from '../../ui/visual_logging/visual_logging.js';
import {commentForbiddenHeaders, isForbiddenHeader} from './FetchHeaderCommenting.js';
import {canPreloadRequest, generatePreloadLink} from './LinkPreloadGenerator.js';
import {
Events,
type EventTypes,
NetworkGroupNode,
type NetworkLogViewInterface,
type NetworkNode,
NetworkRequestNode,
RequestPanelBehavior,
} from './NetworkDataGridNode.js';
import {NetworkFrameGrouper} from './NetworkFrameGrouper.js';
import networkLogViewStyles from './networkLogView.css.js';
import {NetworkLogViewColumns} from './NetworkLogViewColumns.js';
import type {NetworkWaterfallColumn} from './NetworkWaterfallColumn.js';
const UIStrings = {
/**
* @description Text in Network Log View of the Network panel
*/
invertFilter: 'Invert',
/**
* @description Tooltip for the 'invert' checkbox in the Network panel.
*/
invertsFilter: 'Inverts the search filter',
/**
* @description Text in Network Log View of the Network panel
*/
hideDataUrls: 'Hide data URLs',
/**
* @description Data urlfilter ui element title in Network Log View of the Network panel
*/
hidesDataAndBlobUrls: 'Hide \'data:\' and \'blob:\' URLs',
/**
* @description Label for a filter in the Network panel
*/
chromeExtensions: 'Hide extension URLs',
/**
* @description Tooltip for a filter in the Network panel
*/
hideChromeExtension: 'Hide \'chrome-extension://\' URLs',
/**
* @description Aria accessible name in Network Log View of the Network panel
*/
requestTypesToInclude: 'Request types to include',
/**
* @description Label for a checkbox in the Network panel. When checked, only requests with
* blocked response cookies are shown.
*/
hasBlockedCookies: 'Blocked response cookies',
/**
* @description Tooltip for a checkbox in the Network panel. The response to a network request may include a
* cookie (https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies). Such response cookies can
* be malformed or otherwise invalid and the browser may choose to ignore or not accept invalid cookies.
*/
onlyShowRequestsWithBlockedCookies: 'Show only requests with blocked response cookies',
/**
* @description Label for a filter in the Network panel
*/
blockedRequests: 'Blocked requests',
/**
* @description Tooltip for a filter in the Network panel
*/
onlyShowBlockedRequests: 'Show only blocked requests',
/**
* @description Label for a filter in the Network panel
*/
thirdParty: '3rd-party requests',
/**
* @description Tooltip for a filter in the Network panel
*/
onlyShowThirdPartyRequests: 'Show only requests with origin different from page origin',
/**
* @description Text that appears when user drag and drop something (for example, a file) in Network Log View of the Network panel
*/
dropHarFilesHere: 'Drop HAR files here',
/**
* @description Recording text content in Network Log View of the Network panel
*/
recordingNetworkActivity: 'Currently recording network activity',
/**
* @description Shown in the Network Log View of the Network panel when the user has not yet
* recorded any network activity. This is an instruction to the user to reload the page in order to
* show network activity in the current UI.
* @example {Reload page} PH1
* @example {Ctrl + R} PH2
*/
performARequestOrHitSToRecordThe:
'Perform a request or reload the page by using the "{PH1}" button or by pressing {PH2}',
/**
* @description Shown in the Network Log View of the Network panel when the user has not yet
* recorded any network activity. This is an instruction to the user to start recording in order to
* show network activity in the current UI.
* @example {Start recording} PH1
* @example {Ctrl + E} PH2
*/
recordToDisplayNetworkActivity:
'Record network log to display network activity by using the "{PH1}" button or by pressing {PH2}',
/**
* @description Label of a button in the Network Log View of the Network panel.
*/
reloadPage: 'Reload page',
/**
* @description Label of a button in the Network Log View of the Network panel.
*/
startRecording: 'Start recording',
/**
* @description Shown in the Network Log View of the Network panel when the user has not yet
* recorded any network activity.
*/
noNetworkActivityRecorded: 'No network activity recorded',
/**
* @description Text to announce to screen readers that network data is available.
*/
networkDataAvailable: 'Network data available',
/**
* @description Text in Network Log View of the Network panel
* @example {3} PH1
* @example {5} PH2
*/
sSRequests: '{PH1} / {PH2} requests',
/**
* @description Message in the summary toolbar at the bottom of the Network log that shows the compressed size of the
* resources transferred during a selected time frame over the compressed size of all resources transferred during
* the whole network log.
* @example {5 B} PH1
* @example {10 B} PH2
*/
sSTransferred: '{PH1} / {PH2} transferred',
/**
* @description Message in a tooltip that shows the compressed size of the resources transferred during a selected
* time frame over the compressed size of all resources transferred during the whole network log.
* @example {10} PH1
* @example {15} PH2
*/
sBSBTransferredOverNetwork: '{PH1} B / {PH2} B transferred over network',
/**
* @description Text in Network Log View of the Network panel. Appears when a particular network
* resource is selected by the user. Shows how large the selected resource was (PH1) out of the
* total size (PH2).
* @example {40MB} PH1
* @example {50MB} PH2
*/
sSResources: '{PH1} / {PH2} resources',
/**
* @description Text in Network Log View of the Network panel
* @example {40} PH1
* @example {50} PH2
*/
sBSBResourcesLoadedByThePage: '{PH1} B / {PH2} B resources loaded by the page',
/**
* @description Text in Network Log View of the Network panel
* @example {6} PH1
*/
sRequests: '{PH1} requests',
/**
* @description Message in the summary toolbar at the bottom of the Network log that shows the compressed size of
* all resources transferred over network during a network activity log.
* @example {4 B} PH1
*/
sTransferred: '{PH1} transferred',
/**
* @description Message in a tooltip that shows the compressed size of all resources transferred over network during
* a network activity log.
* @example {4} PH1
*/
sBTransferredOverNetwork: '{PH1} B transferred over network',
/**
* @description Text in Network Log View of the Network panel
* @example {4} PH1
*/
sResources: '{PH1} resources',
/**
* @description Text in Network Log View of the Network panel
* @example {10} PH1
*/
sBResourcesLoadedByThePage: '{PH1} B resources loaded by the page',
/**
* @description Text in Network Log View of the Network panel
* @example {120ms} PH1
*/
finishS: 'Finish: {PH1}',
/**
* @description Text in Network Log View of the Network panel
* @example {3000ms} PH1
*/
domcontentloadedS: 'DOMContentLoaded: {PH1}',
/**
* @description Text in Network Log View of the Network panel
* @example {40ms} PH1
*/
loadS: 'Load: {PH1}',
/**
* @description Text for copying
*/
copy: 'Copy',
/**
* @description A context menu command in the Network panel, for copying the URL of the selected request to the clipboard.
*/
copyURL: 'Copy URL',
/**
* @description Text in Network Log View of the Network panel
*/
copyRequestHeaders: 'Copy request headers',
/**
* @description Text in Network Log View of the Network panel
*/
copyResponseHeaders: 'Copy response headers',
/**
* @description Text in Network Log View of the Network panel
*/
copyResponse: 'Copy response',
/**
* @description Text in Network Log View of the Network panel
*/
copyStacktrace: 'Copy stack trace',
/**
* @description A context menu command in the Network panel, for copying to the clipboard.
* PowerShell refers to the format the data will be copied as.
*/
copyAsPowershell: 'Copy as `PowerShell`',
/**
* @description A context menu command in the Network panel, for copying to the clipboard. 'fetch'
* refers to the format the data will be copied as, which is compatible with the fetch web API.
*/
copyAsFetch: 'Copy as `fetch`',
/**
* @description A context menu command in the Network panel, for copying a resource's link element
* to the clipboard. 'preload' refers to the HTML link relation format the data will be copied as.
*/
copyAsPreload: 'Copy as preload element',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
* the developer's clipboard. The command allows the developer to replay this specific network
* request in Node.js, a desktop application/framework. 'Node.js fetch' is a noun phrase for the
* type of request that will be copied.
*/
copyAsNodejsFetch: 'Copy as `fetch` (`Node.js`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable).
*/
copyAsCurlCmd: 'Copy as `cURL` (`cmd`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a Bash script.
*/
copyAsCurlBash: 'Copy as `cURL` (`bash`)',
/**
* @description A context menu command in the Network panel, for copying the URLs of all requestes to the clipboard.
*/
copyAllURLs: 'Copy all URLs',
/**
* @description A context menu command in the Network panel, for copying the URLs of all requestes
* (after applying the Network filter) to the clipboard.
*/
copyAllListedURLs: 'Copy all listed URLs',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a PowerShell script to
*represent all network requests.
*/
copyAllAsPowershell: 'Copy all as `PowerShell`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a PowerShell script to
*represent all network requests (after applying the Network filter).
*/
copyAllListedAsPowershell: 'Copy all listed as `PowerShell`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a 'fetch' command (fetch
*should not be translated) to represent all network requests.
*/
copyAllAsFetch: 'Copy all as `fetch`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a 'fetch' command (fetch
*should not be translated) to represent all network requests (after applying the Network filter).
*/
copyAllListedAsFetch: 'Copy all listed as `fetch`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a Node.js 'fetch' command
*(fetch and Node.js should not be translated) to represent all network requests.
*/
copyAllAsNodejsFetch: 'Copy all as `fetch` (`Node.js`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a Node.js 'fetch' command
*(fetch and Node.js should not be translated) to represent all network requests (after applying
*the Network filter).
*/
copyAllListedAsNodejsFetch: 'Copy all listed as `fetch` (`Node.js`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable) to represent all network requests.
*/
copyAllAsCurlCmd: 'Copy all as `cURL` (`cmd`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable) to represent all network requests (after applying the Network filter).
*/
copyAllListedAsCurlCmd: 'Copy all listed as `cURL` (`cmd`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a Bash script to represent
*all network requests.
*/
copyAllAsCurlBash: 'Copy all as `cURL` (`bash`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with a Bash script to represent
*all network requests (after applying the Network filter).
*/
copyAllListedAsCurlBash: 'Copy all listed as `cURL` (`bash`)',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable).
*/
copyAsCurl: 'Copy as `cURL`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable) to represent all network requests.
*/
copyAllAsCurl: 'Copy all as `cURL`',
/**
* @description Text in Network Log View of the Network panel. An action that copies a command to
*the clipboard. It will copy the command in the format compatible with cURL (a program, not
*translatable) to represent all network requests (after applying the Network filter).
*/
copyAllListedAsCurl: 'Copy all listed as `cURL`',
/**
* @description Text in Network Log View of the Network panel. An action that copies data to the
* clipboard. It will copy the data in the HAR (not translatable) format and scrub all potentially
* sensitive data from the network requests. 'all' refers to every network request that is currently
* shown.
*/
copyAllAsHarSanitized: 'Copy all as `HAR` (sanitized)',
/**
* @description Text in Network Log View of the Network panel. An action that copies data to the
* clipboard. It will copy the data in the HAR (not translatable) format and include potentially
* sensitive data from the network requests. 'all' refers to every network request that is currently
* shown.
*/
copyAllAsHarWithSensitiveData: 'Copy all as `HAR` (with sensitive data)',
/**
* @description Text in Network Log View of the Network panel. An action that copies data to the
* clipboard. It will copy the data in the HAR (not translatable) format and scrub all potentially
* sensitive data from the network requests. 'all' refers to every network request that is currently
* shown (after applying the Network filter).
*/
copyAllListedAsHarSanitized: 'Copy all listed as `HAR` (sanitized)',
/**
* @description Text in Network Log View of the Network panel. An action that copies data to the
* clipboard. It will copy the data in the HAR (not translatable) format and include potentially
* sensitive data from the network requests. 'all' refers to every network request that is currently
* shown (after applying the Network filter).
*/
copyAllListedAsHarWithSensitiveData: 'Copy all listed as `HAR` (with sensitive data)',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
clearBrowserCache: 'Clear browser cache',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
clearBrowserCookies: 'Clear browser cookies',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
throttleRequests: 'Throttle requests',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
throttleRequestUrl: 'Throttle request URL',
/**
* @description A context menu item in the Network Log View of the Network panel
* @example {example.com} PH1
*/
unthrottleS: 'Stop throttling {PH1}',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
throttleRequestDomain: 'Throttle request domain',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
blockRequests: 'Block requests',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
blockRequestUrl: 'Block request URL',
/**
* @description A context menu item in the Network Log View of the Network panel
* @example {example.com} PH1
*/
unblockS: 'Unblock {PH1}',
/**
* @description A context menu item in the Network Log View of the Network panel
*/
blockRequestDomain: 'Block request domain',
/**
* @description Text to resend a network request
*/
resend: 'Resend',
/**
* @description A context menu command in the Network panel that copies a request as an editable
* fetch command and pastes it into the Console for the user to modify before resending.
*/
editAndResendAsFetch: 'Edit and resend as fetch',
/**
* @description Console message that appears when using "Edit and resend as fetch" feature.
* Indicates that a resendable copy of a request has been placed in the console.
* @example {GET} PH1
* @example {api/data} PH2
*/
resendableCopyOfRequest: 'Resendable copy of {PH1} request to {PH2}',
/**
* @description Comment added before a generated fetch command, indicating which execution
* context the original request was sent from.
* @example {top} PH1
*/
originallyCalledFromContext: '// Originally called from {PH1} context',
/**
* @description Comment added before a generated fetch command, advising the user to select
* the execution context in the Console toolbar to resend from the same context.
*/
selectExecutionContextInConsole: '// To resend from the same execution context, select it in the Console’s toolbar',
/**
* @description Comment added after a generated fetch command, inviting the user to edit before resending.
*/
editAndEnterToResend: '// Make any edits, then ENTER to resend',
/**
* @description Text in Network Log View of the Network panel
*/
areYouSureYouWantToClearBrowser: 'Are you sure you want to clear browser cache?',
/**
* @description Text in Network Log View of the Network panel
*/
areYouSureYouWantToClearBrowserCookies: 'Are you sure you want to clear browser cookies?',
/**
* @description A context menu item in the Network Log View of the Network panel
* for creating a header override
*/
overrideHeaders: 'Override headers',
/**
* @description Tooltip for the Show only/Hide requests dropdown of the filterbar
*/
showOnlyHideRequests: 'Show only/hide requests',
/**
* @description Text for the Show only/Hide requests dropdown button of the filterbar
*/
moreFilters: 'More filters',
/**
* @description A comment in a generated command indicating that the URL scheme is unsupported. The placeholder is the comment prefix (e.g. '//' or '#').
* @example {//} PH1
*/
unsupportedUrlScheme: '{PH1} Unsupported URL scheme',
} as const;
const str_ = i18n.i18n.registerUIStrings('panels/network/NetworkLogView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const enum FetchStyle {
BROWSER = 0,
NODE_JS = 1,
}
export interface ViewInput {
recording: boolean;
showRecordingHint: boolean;
recordingActionShortcut: string;
onRecordingAction?: () => void;
nodeCount: number;
selectedNodeCount: number;
transferSize: number;
selectedTransferSize: number;
resourceSize: number;
selectedResourceSize: number;
baseTime: number;
maxTime: number;
domContentLoadedTime: number;
loadTime: number;
isNodeSelected: boolean;
isGridFocused: boolean;
isWaterfallVisible: boolean;
// TODO(crbug.com/414631097): Remove once NetworkLogViewColumns is migrated to UI eng vision.
dataGridWidget: DataGrid.DataGrid.DataGridWidget<NetworkNode>;
waterfallColumn: NetworkWaterfallColumn;
}
export type View = (input: ViewInput, output: undefined, target: HTMLElement) => void;
export const DEFAULT_VIEW: View = (input, _output, target) => {
const classes: string[] = [];
if (!input.isNodeSelected) {
classes.push('no-node-selected');
}
if (input.isGridFocused) {
classes.push('grid-focused');
}
if (input.isWaterfallVisible) {
classes.push('has-waterfall');
}
const actionName = input.recording ? 'inspector-main.reload' : 'network.toggle-recording';
const header = input.recording ? i18nString(UIStrings.recordingNetworkActivity) :
i18nString(UIStrings.noNetworkActivityRecorded);
const instruction =
input.recording ? UIStrings.performARequestOrHitSToRecordThe : UIStrings.recordToDisplayNetworkActivity;
const buttonText = input.recording ? i18nString(UIStrings.reloadPage) : i18nString(UIStrings.startRecording);
// eslint-disable-next-line @devtools/l10n-i18nString-call-only-with-uistrings
const description = input.recordingActionShortcut ? i18nString(instruction, {
PH1: buttonText,
PH2: input.recordingActionShortcut,
}) :
'';
const summaryItems: Array<{
text: Common.UIString.LocalizedString,
title: Common.UIString.LocalizedString,
color?: string,
}> = [];
if (!input.showRecordingHint && input.nodeCount > 0) {
const appendChunk =
(chunk: Common.UIString.LocalizedString, title?: Common.UIString.LocalizedString, color?: string): void => {
summaryItems.push({text: chunk, title: title ?? chunk, color});
};
if (input.selectedNodeCount !== input.nodeCount) {
appendChunk(i18nString(UIStrings.sSRequests, {PH1: input.selectedNodeCount, PH2: input.nodeCount}));
appendChunk(i18nString(UIStrings.sSTransferred, {
PH1: i18n.ByteUtilities.formatBytesToKb(input.selectedTransferSize),
PH2: i18n.ByteUtilities.formatBytesToKb(input.transferSize),
}),
i18nString(UIStrings.sBSBTransferredOverNetwork, {
PH1: input.selectedTransferSize,
PH2: input.transferSize,
}));
appendChunk(i18nString(UIStrings.sSResources, {
PH1: i18n.ByteUtilities.formatBytesToKb(input.selectedResourceSize),
PH2: i18n.ByteUtilities.formatBytesToKb(input.resourceSize),
}),
i18nString(UIStrings.sBSBResourcesLoadedByThePage, {
PH1: input.selectedResourceSize,
PH2: input.resourceSize,
}));
} else {
appendChunk(i18nString(UIStrings.sRequests, {PH1: input.nodeCount}));
appendChunk(i18nString(UIStrings.sTransferred, {PH1: i18n.ByteUtilities.bytesToString(input.transferSize)}),
i18nString(UIStrings.sBTransferredOverNetwork, {PH1: input.transferSize}));
appendChunk(i18nString(UIStrings.sResources, {PH1: i18n.ByteUtilities.bytesToString(input.resourceSize)}),
i18nString(UIStrings.sBResourcesLoadedByThePage, {PH1: input.resourceSize}));
}
if (input.baseTime !== -1 && input.maxTime !== -1) {
appendChunk(i18nString(UIStrings.finishS, {
PH1: i18n.TimeUtilities.secondsToString(input.maxTime - input.baseTime),
}));
if (input.domContentLoadedTime !== -1 && input.domContentLoadedTime > input.baseTime) {
const domContentLoadedText = i18nString(UIStrings.domcontentloadedS, {
PH1: i18n.TimeUtilities.secondsToString(input.domContentLoadedTime - input.baseTime),
});
appendChunk(domContentLoadedText, undefined, NetworkLogView.getDCLEventColor());
}
if (input.loadTime !== -1) {
const loadText = i18nString(UIStrings.loadS, {
PH1: i18n.TimeUtilities.secondsToString(input.loadTime - input.baseTime),
});
appendChunk(loadText, undefined, NetworkLogView.getLoadEventColor());
}
}
}
// clang-format off
render(html`
<style>${networkLogViewStyles}</style>
<style>@scope to (devtools-widget > *) { ${dataGridAiButtonStyles} }</style>
<devtools-split-view
direction="column"
sidebar-position="second"
name="network-panel-split-view-waterfall"
sidebar-initial-size="200"
show=${input.isWaterfallVisible ? 'both' : 'main'}
aria-hidden=${input.showRecordingHint}>
<div
slot="main"
${UI.Widget.widget(UI.Widget.WrapperWidget, {widget: input.dataGridWidget})}>
</div>
<div
slot="sidebar"
${UI.Widget.widget(UI.Widget.WrapperWidget, {
widget: input.isWaterfallVisible ? input.waterfallColumn : null,
})}>
</div>
</devtools-split-view>
${input.showRecordingHint ? html`
<devtools-widget
class="network-status-pane"
${UI.Widget.widget(UI.EmptyWidget.EmptyWidget, {
header,
text: description,
link: 'https://developer.chrome.com/docs/devtools/network/' as Platform.DevToolsPath.UrlString,
})}>
${input.onRecordingAction ? html`
<devtools-button
.variant=${Buttons.Button.Variant.TONAL}
.jslogContext=${actionName}
@click=${input.onRecordingAction}>
${buttonText}
</devtools-button>
` : nothing}
</devtools-widget>
` : nothing}
<devtools-toolbar
class="network-summary-bar"
role="status"
aria-hidden=${input.showRecordingHint}>
${summaryItems.map((item, index) => html`
${index > 0 ? html`<div class="toolbar-divider toolbar-item"></div>` : nothing}
<div
class="toolbar-text toolbar-item"
title=${item.title}
aria-label=${item.title}
style=${Directives.styleMap({color: item.color ? `var(${item.color})` : undefined})}>
${item.text}
</div>
`)}
</devtools-toolbar>
`, target, {
container: {
attributes: {
id: 'network-container',
},
classes,
},
});
// clang-format on
};
const NetworkLogViewBase: Common.ObjectWrapper.EventMixin<EventTypes, typeof UI.Widget.VBox> =
Common.ObjectWrapper.eventMixin(
UI.Widget.VBox,
);
export class NetworkLogView extends NetworkLogViewBase implements
SDK.TargetManager.SDKModelObserver<SDK.NetworkManager.NetworkManager>, NetworkLogViewInterface {
readonly #view: View;
readonly #networkInvertFilterSetting: Common.Settings.Setting<boolean>;
readonly #networkHideDataURLSetting: Common.Settings.Setting<boolean>;
readonly #networkHideChromeExtensions: Common.Settings.Setting<boolean>;
readonly #networkShowBlockedCookiesOnlySetting: Common.Settings.Setting<boolean>;
readonly #networkOnlyBlockedRequestsSetting: Common.Settings.Setting<boolean>;
readonly #networkOnlyThirdPartySetting: Common.Settings.Setting<boolean>;
readonly #networkResourceTypeFiltersSetting: Common.Settings.Setting<Record<string, boolean>>;
readonly #networkShowOptionsToGenerateHarWithSensitiveData: Common.Settings.Setting<boolean>;
readonly #progressBarContainer: Element;
readonly #networkLogLargeRowsSetting: Common.Settings.Setting<boolean>;
#rowHeight: number;
readonly #timeCalculator: NetworkTimeCalculator.NetworkTransferTimeCalculator;
readonly #durationCalculator: NetworkTimeCalculator.NetworkTimeCalculator;
#calculator: NetworkTimeCalculator.NetworkTimeCalculator;
readonly #columns: NetworkLogViewColumns;
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private staleRequests: Set<SDK.NetworkRequest.NetworkRequest>;
#mainRequestLoadTime: number;
#mainRequestDOMContentLoadedTime: number;
#filters: Filter[];
#timeFilter: Filter|null;
#hoveredNode: NetworkNode|null;
#showRecordingHintState: boolean;
#nodeCount: number;
#selectedNodeCount: number;
#transferSize: number;
#selectedTransferSize: number;
#resourceSize: number;
#selectedResourceSize: number;
#baseTime: number;
#maxTime: number;
#isNodeSelected: boolean;
#isGridFocused: boolean;
#highlightedNode: NetworkRequestNode|null;
readonly #linkifier: Components.Linkifier.Linkifier;
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private recording: boolean;
#needsRefresh: boolean;
readonly #headerHeight: number;
readonly #groupLookups: Map<string, GroupLookupInterface>;
#activeGroupLookup: GroupLookupInterface|null;
readonly #textFilterUI: UI.FilterBar.TextFilterUI;
readonly #invertFilterUI: UI.FilterBar.CheckboxFilterUI;
readonly #moreFiltersDropDownUI: MoreFiltersDropDownUI|undefined;
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private readonly resourceCategoryFilterUI: UI.FilterBar.NamedBitSetFilterUI;
readonly #filterParser: TextUtils.TextUtils.FilterParser;
readonly #suggestionBuilder: UI.FilterSuggestionBuilder.FilterSuggestionBuilder;
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private dataGrid: DataGrid.SortableDataGrid.SortableDataGrid<NetworkNode>;
readonly #filterBar: UI.FilterBar.FilterBar;
readonly #textFilterSetting: Common.Settings.Setting<string>;
#networkRequestToNode: WeakMap<SDK.NetworkRequest.NetworkRequest, NetworkRequestNode>;
constructor(filterBar: UI.FilterBar.FilterBar, progressBarContainer: Element,
networkLogLargeRowsSetting: Common.Settings.Setting<boolean>, view: View = DEFAULT_VIEW) {
super();
this.#view = view;
this.setMinimumSize(50, 64);
this.#networkRequestToNode = new WeakMap();
this.#networkInvertFilterSetting =
Common.Settings.Settings.instance().createSetting('network-invert-filter', false);
this.#networkHideDataURLSetting = Common.Settings.Settings.instance().createSetting('network-hide-data-url', false);
this.#networkHideChromeExtensions =
Common.Settings.Settings.instance().createSetting('network-hide-chrome-extensions', false);
this.#networkShowBlockedCookiesOnlySetting =
Common.Settings.Settings.instance().createSetting('network-show-blocked-cookies-only-setting', false);
this.#networkOnlyBlockedRequestsSetting =
Common.Settings.Settings.instance().createSetting('network-only-blocked-requests', false);
this.#networkOnlyThirdPartySetting =
Common.Settings.Settings.instance().createSetting('network-only-third-party-setting', false);
this.#networkResourceTypeFiltersSetting =
Common.Settings.Settings.instance().createSetting('network-resource-type-filters', {});
this.#networkShowOptionsToGenerateHarWithSensitiveData = Common.Settings.Settings.instance().resolve(
Settings.NetworkSettings.showOptionsToGenerateHarWithSensitiveDataSettingDescriptor);
this.#progressBarContainer = progressBarContainer;
this.#networkLogLargeRowsSetting = networkLogLargeRowsSetting;
this.#networkLogLargeRowsSetting.addChangeListener(updateRowHeight.bind(this), this);
function updateRowHeight(this: NetworkLogView): void {
this.#rowHeight = Boolean(this.#networkLogLargeRowsSetting.get()) ? 41 : 21;
}
this.#rowHeight = 0;
updateRowHeight.call(this);
this.#timeCalculator = new NetworkTimeCalculator.NetworkTransferTimeCalculator();
this.#durationCalculator = new NetworkTimeCalculator.NetworkTransferDurationCalculator();
this.#calculator = this.#timeCalculator;
this.#columns =
new NetworkLogViewColumns(this, this.#timeCalculator, this.#durationCalculator, networkLogLargeRowsSetting);
this.staleRequests = new Set();
this.#mainRequestLoadTime = -1;
this.#mainRequestDOMContentLoadedTime = -1;
this.#filters = [];
this.#timeFilter = null;
this.#hoveredNode = null;
this.#showRecordingHintState = false;
this.#nodeCount = 0;
this.#selectedNodeCount = 0;
this.#transferSize = 0;
this.#selectedTransferSize = 0;
this.#resourceSize = 0;
this.#selectedResourceSize = 0;
this.#baseTime = -1;
this.#maxTime = -1;
this.#isNodeSelected = false;
this.#isGridFocused = false;
this.#highlightedNode = null;
this.#linkifier = new Components.Linkifier.Linkifier();
this.recording = false;
this.#needsRefresh = false;
this.#headerHeight = 0;
this.#groupLookups = new Map();
this.#groupLookups.set('Frame', new NetworkFrameGrouper(this));
this.#activeGroupLookup = null;
this.#textFilterUI = new UI.FilterBar.TextFilterUI();
this.#textFilterUI.addEventListener(UI.FilterBar.FilterUIEvents.FILTER_CHANGED, this.#filterChanged, this);
filterBar.addFilter(this.#textFilterUI);
this.#invertFilterUI = new UI.FilterBar.CheckboxFilterUI(i18nString(UIStrings.invertFilter), true,
this.#networkInvertFilterSetting, 'invert-filter');
this.#invertFilterUI.addEventListener(UI.FilterBar.FilterUIEvents.FILTER_CHANGED, this.#filterChanged.bind(this),
this);
UI.Tooltip.Tooltip.install(this.#invertFilterUI.element(), i18nString(UIStrings.invertsFilter));
filterBar.addFilter(this.#invertFilterUI);
filterBar.addDivider();
const filterItems =
Object.entries(Common.ResourceType.resourceCategories).map(([key, category]) => ({
name: category.name,
label: () => category.shortTitle(),
title: category.title(),
jslogContext:
Platform.StringUtilities.toKebabCase(key),
}));
this.#moreFiltersDropDownUI = new MoreFiltersDropDownUI();
this.#moreFiltersDropDownUI.addEventListener(UI.FilterBar.FilterUIEvents.FILTER_CHANGED, this.#filterChanged, this);
filterBar.addFilter(this.#moreFiltersDropDownUI);
this.resourceCategoryFilterUI =
new UI.FilterBar.NamedBitSetFilterUI(filterItems, this.#networkResourceTypeFiltersSetting);
UI.ARIAUtils.setLabel(this.resourceCategoryFilterUI.element(), i18nString(UIStrings.requestTypesToInclude));
this.resourceCategoryFilterUI.addEventListener(UI.FilterBar.FilterUIEvents.FILTER_CHANGED,
this.#filterChanged.bind(this), this);
filterBar.addFilter(this.resourceCategoryFilterUI);
this.#filterParser = new TextUtils.TextUtils.FilterParser(searchKeys);
this.#suggestionBuilder =
new UI.FilterSuggestionBuilder.FilterSuggestionBuilder(searchKeys, NetworkLogView.#sortSearchValues);
this.#resetSuggestionBuilder();
this.dataGrid = this.#columns.dataGrid();
this.#setupDataGrid();
this.#columns.sortByCurrentColumn();
filterBar.filterButton().addEventListener(
UI.Toolbar.ToolbarButton.Events.CLICK, this.dataGrid.scheduleUpdate.bind(this.dataGrid, true /* isFromUser */));
new UI.DropTarget.DropTarget(this.element, [UI.DropTarget.Type.File], i18nString(UIStrings.dropHarFilesHere),
this.#handleDrop.bind(this));
Common.Settings.Settings.instance()
.resolve(Settings.NetworkSettings.colorCodeResourceTypesSettingDescriptor)
.addChangeListener(this.#invalidateAllItems.bind(this, false), this);
SDK.TargetManager.TargetManager.instance().observeModels(SDK.NetworkManager.NetworkManager, this, {scoped: true});
Logs.NetworkLog.NetworkLog.instance().addEventListener(Logs.NetworkLog.Events.RequestAdded, this.#onRequestUpdated,
this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(Logs.NetworkLog.Events.RequestUpdated,
this.#onRequestUpdated, this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(Logs.NetworkLog.Events.RequestRemoved,
this.#onRequestRemoved, this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(Logs.NetworkLog.Events.Reset, this.reset, this);
this.#updateGroupByFrame();
Common.Settings.Settings.instance()
.resolve(Settings.NetworkSettings.groupByFrameSettingDescriptor)
.addChangeListener(() => this.#updateGroupByFrame());
this.#filterBar = filterBar;
this.#textFilterSetting = Common.Settings.Settings.instance().createSetting('network-text-filter', '');
if (this.#textFilterSetting.get()) {
this.#textFilterUI.setValue(this.#textFilterSetting.get());
}
this.requestUpdate();
}
override performUpdate(): void {
const actionRegistry = UI.ActionRegistry.ActionRegistry.instance();
const actionName = this.recording ? 'inspector-main.reload' : 'network.toggle-recording';
const action = actionRegistry.hasAction(actionName) ? actionRegistry.getAction(actionName) : null;
const shortcutTitle = UI.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction(actionName) ?? '';
this.#view(
{
recording: this.recording,
showRecordingHint: this.#showRecordingHintState,
recordingActionShortcut: shortcutTitle,
onRecordingAction: shortcutTitle && action ?
() => {
void action.execute();
} :
undefined,
nodeCount: this.#nodeCount,
selectedNodeCount: this.#selectedNodeCount,
transferSize: this.#transferSize,
selectedTransferSize: this.#selectedTransferSize,
resourceSize: this.#resourceSize,
selectedResourceSize: this.#selectedResourceSize,
baseTime: this.#baseTime,
maxTime: this.#maxTime,
domContentLoadedTime: this.#mainRequestDOMContentLoadedTime,
loadTime: this.#mainRequestLoadTime,
isNodeSelected: this.#isNodeSelected,
isGridFocused: this.#isGridFocused,
isWaterfallVisible: this.#columns.isWaterfallVisible(),
dataGridWidget: this.dataGrid.asWidget(),
waterfallColumn: this.#columns.waterfall(),
},
undefined,
this.contentElement,
);
this.#columns.updateWaterfallScroller();
}
#updateGroupByFrame(): void {
const value =
Common.Settings.Settings.instance().resolve(Settings.NetworkSettings.groupByFrameSettingDescriptor).get();
this.#setGrouping(value ? 'Frame' : null);
}
static #sortSearchValues(key: string, values: string[]): void {
if (key === NetworkForward.UIFilter.FilterType.Priority) {
values.sort((a, b) => {
const aPriority = PerfUI.NetworkPriorities.uiLabelToNetworkPriority(a);
const bPriority = PerfUI.NetworkPriorities.uiLabelToNetworkPriority(b);
return PerfUI.NetworkPriorities.networkPriorityWeight(aPriority) -
PerfUI.NetworkPriorities.networkPriorityWeight(bPriority);
});
} else {
values.sort();
}
}
static #negativeFilter(filter: Filter, request: SDK.NetworkRequest.NetworkRequest): boolean {
return !filter(request);
}
static #requestHostAndPathFilter(regex: RegExp|null, request: SDK.NetworkRequest.NetworkRequest): boolean {
if (!regex) {
return false;
}
return regex.test(request.parsedURL.urlWithoutScheme());
}
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private static subdomains(domain: string): string[] {
const result = [domain];
let indexOfPeriod = domain.indexOf('.');
while (indexOfPeriod !== -1) {
result.push('*' + domain.substring(indexOfPeriod));
indexOfPeriod = domain.indexOf('.', indexOfPeriod + 1);
}
return result;
}
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private static createRequestDomainFilter(value: string): Filter {
const escapedPattern = value.split('*').map(Platform.StringUtilities.escapeForRegExp).join('.*');
return NetworkLogView.#requestDomainFilter.bind(null, new RegExp('^' + escapedPattern + '$', 'i'));
}
static #requestDomainFilter(regex: RegExp, request: SDK.NetworkRequest.NetworkRequest): boolean {
return regex.test(request.domain);
}
static #runningRequestFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return !request.finished;
}
static #fromCacheRequestFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.cached();
}
static #interceptedByServiceWorkerFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.fetchedViaServiceWorker;
}
static #initiatedByServiceWorkerFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.initiatedByServiceWorker();
}
static #linkPreloadRequestFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.isLinkPreload();
}
static #requestResponseHeaderFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.responseHeaderValue(value) !== undefined;
}
static #requestRequestHeaderFilter(headerName: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.requestHeaders().some(header => header.name.toLowerCase() === headerName.toLowerCase());
}
static #requestResponseHeaderSetCookieFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
// Multiple Set-Cookie headers in the request are concatenated via space. Only
// filter via `includes` instead of strict equality.
return Boolean(request.responseHeaderValue('Set-Cookie')?.includes(value));
}
static #requestMethodFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.requestMethod === value;
}
static #requestPriorityFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.priority() === value;
}
static #requestMimeTypeFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.mimeType === value;
}
static #requestMixedContentFilter(value: NetworkForward.UIFilter.MixedContentFilterValues,
request: SDK.NetworkRequest.NetworkRequest): boolean {
if (value === NetworkForward.UIFilter.MixedContentFilterValues.DISPLAYED) {
return request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable;
}
if (value === NetworkForward.UIFilter.MixedContentFilterValues.BLOCKED) {
return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && request.wasBlocked();
}
if (value === NetworkForward.UIFilter.MixedContentFilterValues.BLOCK_OVERRIDDEN) {
return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && !request.wasBlocked();
}
if (value === NetworkForward.UIFilter.MixedContentFilterValues.ALL) {
return request.mixedContentType !== Protocol.Security.MixedContentType.None;
}
return false;
}
static #requestSchemeFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.scheme === value;
}
static #requestCookieDomainFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.allCookiesIncludingBlockedOnes().some(cookie => cookie.domain() === value);
}
static #requestCookieNameFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.allCookiesIncludingBlockedOnes().some(cookie => cookie.name() === value);
}
static #requestCookiePathFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.allCookiesIncludingBlockedOnes().some(cookie => cookie.path() === value);
}
static #requestCookieValueFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.allCookiesIncludingBlockedOnes().some(cookie => cookie.value() === value);
}
static #requestSetCookieDomainFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.responseCookies.some(cookie => cookie.domain() === value);
}
static #requestSetCookieNameFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.responseCookies.some(cookie => cookie.name() === value);
}
static #requestSetCookieValueFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.responseCookies.some(cookie => cookie.value() === value);
}
static #requestSizeLargerThanFilter(value: number, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.transferSize >= value;
}
static #statusCodeFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return (String(request.statusCode)) === value;
}
static #hasOverridesFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
if (!value) {
return false;
}
if (value === overrideFilter.no) {
return request.overrideTypes.length === 0;
}
if (value === overrideFilter.yes) {
return request.overrideTypes.length > 0;
}
if (value === overrideFilter.content) {
return request.overrideTypes.includes('content');
}
if (value === overrideFilter.headers) {
return request.overrideTypes.includes('headers');
}
return request.overrideTypes.join(',').includes(value);
}
static getHTTPRequestsFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.parsedURL.isValid && (request.scheme in HTTPSchemas);
}
static #resourceTypeFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
return request.resourceType().name() === value;
}
static #requestUrlFilter(value: string, request: SDK.NetworkRequest.NetworkRequest): boolean {
const regex = new RegExp(Platform.StringUtilities.escapeForRegExp(value), 'i');
return regex.test(request.url());
}
static #requestTimeFilter(windowStart: number, windowEnd: number,
request: SDK.NetworkRequest.NetworkRequest): boolean {
if (request.issueTime() > windowEnd) {
return false;
}
if (request.endTime !== -1 && request.endTime < windowStart) {
return false;
}
return true;
}
static #copyRequestHeaders(request: SDK.NetworkRequest.NetworkRequest): void {
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(request.requestHeadersText());
}
static #copyResponseHeaders(request: SDK.NetworkRequest.NetworkRequest): void {
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(request.responseHeadersText);
}
static async #copyResponse(request: SDK.NetworkRequest.NetworkRequest): Promise<void> {
const contentData = await request.requestContentData();
let content: string;
if (TextUtils.ContentData.ContentData.isError(contentData)) {
content = '';
} else if (!contentData.isTextContent) {
content = contentData.asDataUrl() ?? '';
} else {
content = contentData.text;
}
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(content);
}
#handleDrop(dataTransfer: DataTransfer): void {
const items = dataTransfer.items;
if (!items.length) {
return;
}
const file = items[0].getAsFile();
if (file) {
void this.onLoadFromFile(file);
}
}
async onLoadFromFile(file: File): Promise<void> {
const outputStream = new Common.StringOutputStream.StringOutputStream();
const reader = new Bindings.FileUtils.ChunkedFileReader(file, /* chunkSize */ 10000000);
const success = await reader.read(outputStream);
if (!success) {
const error = reader.error();
if (error) {
this.#harLoadFailed(error.message);
}
return;
}
let harRoot;
try {
// HARRoot and JSON.parse might throw.
harRoot = new HAR.HARFormat.HARRoot(JSON.parse(outputStream.data()));
} catch (e) {
this.#harLoadFailed(e);
return;
}
Logs.NetworkLog.NetworkLog.instance().importRequests(HAR.Importer.Importer.requestsFromHARLog(harRoot.log));
}
#harLoadFailed(message: string): void {
Common.Console.Console.instance().error('Failed to load HAR file with following error: ' + message);
}
#setGrouping(groupKey: string|null): void {
if (this.#activeGroupLookup) {
this.#activeGroupLookup.reset();
}
const groupLookup = groupKey ? this.#groupLookups.get(groupKey) || null : null;
this.#activeGroupLookup = groupLookup;
this.#invalidateAllItems();
}
nodeForRequest(request: SDK.NetworkRequest.NetworkRequest): NetworkRequestNode|null {
return this.#networkRequestToNode.get(request) || null;
}
headerHeight(): number {
return this.#headerHeight;
}
setRecording(recording: boolean): void {
this.recording = recording;
this.#updateSummaryBar();
}
columns(): NetworkLogViewColumns {
return this.#columns;
}
modelAdded(networkManager: SDK.NetworkManager.NetworkManager): void {
// TODO(allada) Remove dependency on networkManager and instead use NetworkLog and PageLoad for needed data.
const target = networkManager.target();
if (target.outermostTarget() !== target) {
return;
}
const resourceTreeModel = target.model(SDK.ResourceTreeModel.ResourceTreeModel);
if (resourceTreeModel) {
resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.Load, this.#loadEventFired, this);
resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,
this.#domContentLoadedEventFired, this);
}
for (const request of Logs.NetworkLog.NetworkLog.instance().requests()) {
if (this.#isInScope(request)) {
this.#refreshRequest(request);
}
}
}
modelRemoved(networkManager: SDK.NetworkManager.NetworkManager): void {
const target = networkManager.target();
if (target.outermostTarget() !== target) {
return;
}
const resourceTreeModel = target.model(SDK.ResourceTreeModel.ResourceTreeModel);
if (resourceTreeModel) {
resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.Load, this.#loadEventFired, this);
resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded,
this.#domContentLoadedEventFired, this);
}
const preserveLog =
Common.Settings.Settings.instance().resolve(SDK.SDKSettings.preserveNetworkLogSettingDescriptor).get();
if (!preserveLog) {
this.reset();
}
}
linkifier(): Components.Linkifier.Linkifier {
return this.#linkifier;
}
setWindow(start: number, end: number): void {
if (!start && !end) {
this.#timeFilter = null;
this.#timeCalculator.setWindow(null);
} else {
this.#timeFilter = NetworkLogView.#requestTimeFilter.bind(null, start, end);
this.#timeCalculator.setWindow(new NetworkTimeCalculator.NetworkTimeBoundary(start, end));
}
this.#filterRequests();
}
resetFocus(): void {
this.dataGrid.element.focus();
}
#resetSuggestionBuilder(): void {
this.#suggestionBuilder.clear();
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Is,
NetworkForward.UIFilter.IsFilterType.RUNNING);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Is,
NetworkForward.UIFilter.IsFilterType.FROM_CACHE);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Is,
NetworkForward.UIFilter.IsFilterType.SERVICE_WORKER_INTERCEPTED);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Is,
NetworkForward.UIFilter.IsFilterType.SERVICE_WORKER_INITIATED);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Is,
NetworkForward.UIFilter.IsFilterType.PRELOAD);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.LargerThan, '100');
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.LargerThan, '10k');
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.LargerThan, '1M');
this.#textFilterUI.setSuggestionProvider(this.#suggestionBuilder.completions.bind(this.#suggestionBuilder));
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasOverrides, overrideFilter.yes);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasOverrides, overrideFilter.no);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasOverrides, overrideFilter.content);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasOverrides, overrideFilter.headers);
}
#filterChanged(): void {
this.removeAllNodeHighlights();
this.#parseFilterQuery(this.#textFilterUI.value(), this.#invertFilterUI.checked());
this.#filterRequests();
this.#textFilterSetting.set(this.#textFilterUI.value());
this.#columns.filterChanged();
}
async resetFilter(): Promise<void> {
this.#textFilterUI.clear();
}
#showRecordingHint(): void {
this.#showRecordingHintState = true;
this.#setHidden(true);
this.requestUpdate();
}
#hideRecordingHint(): void {
this.#setHidden(false);
if (this.#showRecordingHintState) {
this.#showRecordingHintState = false;
UI.ARIAUtils.LiveAnnouncer.alert(i18nString(UIStrings.networkDataAvailable));
this.requestUpdate();
}
}
#setHidden(value: boolean): void {
this.dataGrid.setInert(value);
}
override elementsToRestoreScrollPositionsFor(): Element[] {
if (!this.dataGrid) // Not initialized yet.
{
return [];
}
return [this.dataGrid.scrollContainer];
}
columnExtensionResolved(): void {
this.#invalidateAllItems(true);
}
#setupDataGrid(): DataGrid.SortableDataGrid.SortableDataGrid<NetworkNode> {
this.dataGrid.setRowContextMenuCallback((contextMenu, node) => {
const request = (node as NetworkNode).request();
if (request) {
this.handleContextMenuForRequest(contextMenu, request);
}
});
this.dataGrid.setEnableAutoScrollToBottom(true);
this.dataGrid.setName('network-log');
this.dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.LAST);
this.dataGrid.element.classList.add('network-log-grid');
this.dataGrid.element.addEventListener('mousemove', this.#dataGridMouseMove.bind(this), true);
this.dataGrid.element.addEventListener('mouseleave', () => this.#setHoveredNode(null), true);
this.dataGrid.element.addEventListener('keydown', event => {
if (event.key === 'ArrowRight' && this.dataGrid.selectedNode) {
const initiatorLink = this.dataGrid.selectedNode.element().querySelector('button.devtools-link');
if (initiatorLink) {
(initiatorLink as HTMLElement).focus();
}
}
if (Platform.KeyboardUtilities.isEnterOrSpaceKey(event)) {
this.dispatchEventToListeners(
Events.RequestActivated, {showPanel: RequestPanelBehavior.ShowPanel, takeFocus: true});
event.consume(true);
}
});
this.dataGrid.element.addEventListener('keyup', event => {
if ((event.key === 'r' || event.key === 'R') && this.dataGrid.selectedNode) {
const request = (this.dataGrid.selectedNode as NetworkNode).request();
if (!request) {
return;
}
if (SDK.NetworkManager.NetworkManager.canResendRequest(request, true)) {
SDK.NetworkManager.NetworkManager.replayRequest(request);
void VisualLogging.logKeyDown(this.dataGrid.selectedNode.element(), event, 'resend');
}
}
});
this.dataGrid.element.addEventListener('focus', this.#onDataGridFocus.bind(this), true);
this.dataGrid.element.addEventListener('blur', this.#onDataGridBlur.bind(this), true);
return this.dataGrid;
}
#dataGridMouseMove(event: MouseEvent): void {
const mouseEvent = event;
const node = (this.dataGrid.dataGridNodeFromNode((mouseEvent.target as Node)));
const highlightInitiatorChain = mouseEvent.shiftKey;
this.#setHoveredNode(node as NetworkNode, highlightInitiatorChain);
}
hoveredNode(): NetworkNode|null {
return this.#hoveredNode;
}
#setHoveredNode(node: NetworkNode|null, highlightInitiatorChain?: boolean): void {
if (this.#hoveredNode) {
this.#hoveredNode.setHovered(false, false);
}
this.#hoveredNode = node;
if (this.#hoveredNode) {
this.#hoveredNode.setHovered(true, Boolean(highlightInitiatorChain));
}
}
#updateSummaryBar(): void {
let transferSize = 0;
let resourceSize = 0;
let selectedNodeNumber = 0;
let selectedTransferSize = 0;
let selectedResourceSize = 0;
let baseTime = -1;
let maxTime = -1;
let nodeCount = 0;
for (const request of Logs.NetworkLog.NetworkLog.instance().requests()) {
const node = this.#networkRequestToNode.get(request);
if (!node) {
continue;
}
nodeCount++;
const requestTransferSize = request.transferSize;
transferSize += requestTransferSize;
const requestResourceSize = request.resourceSize;
resourceSize += requestResourceSize;
if (!filteredNetworkRequests.has(node)) {
selectedNodeNumber++;
selectedTransferSize += requestTransferSize;
selectedResourceSize += requestResourceSize;
}
const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request);
// TODO(allada) inspectedURL should be stored in PageLoad used instead of target so HAR requests can have an
// inspected url.
if (networkManager && request.url() === networkManager.target().inspectedURL() &&
request.resourceType() === Common.ResourceType.resourceTypes.Document &&
networkManager.target().parentTarget()?.type() !== SDK.Target.Type.FRAME) {
// If the primary main frame's document was fetched from the prefetch cache,
// we should use the issueTime (i.e. when the navigation request was about to start)
// instead of startTime, which is when the prefetch network request started
// (which is typically well before the navigation starts).
baseTime = request.fromPrefetchCache() ? request.issueTime() : request.startTime;
}
if (request.endTime > maxTime) {
maxTime = request.endTime;
}
}
this.#nodeCount = nodeCount;
this.#selectedNodeCount = selectedNodeNumber;
this.#transferSize = transferSize;
this.#selectedTransferSize = selectedTransferSize;
this.#resourceSize = resourceSize;
this.#selectedResourceSize = selectedResourceSize;
this.#baseTime = baseTime;
this.#maxTime = maxTime;
if (!nodeCount) {
this.#showRecordingHint();
return;
}
this.#hideRecordingHint();
this.requestUpdate();
}
scheduleRefresh(): void {
if (this.#needsRefresh) {
return;
}
this.#needsRefresh = true;
if (this.isShowing()) {
void RenderCoordinator.write('NetworkLogView.render', this.refresh.bind(this));
}
}
addFilmStripFrames(times: number[]): void {
this.#columns.addEventDividers(times, 'network-frame-divider');
}
selectFilmStripFrame(time: number): void {
this.#columns.selectFilmStripFrame(time);
}
clearFilmStripFrame(): void {
this.#columns.clearFilmStripFrame();
}
#refreshIfNeeded(): void {
if (this.#needsRefresh) {
this.refresh();
}
}
#invalidateAllItems(deferUpdate?: boolean): void {
this.staleRequests = new Set(Logs.NetworkLog.NetworkLog.instance().requests().filter(this.#isInScope));
if (deferUpdate) {
this.scheduleRefresh();
} else {
this.refresh();
}
}
timeCalculator(): NetworkTimeCalculator.NetworkTransferTimeCalculator {
return this.#timeCalculator;
}
calculator(): NetworkTimeCalculator.NetworkTimeCalculator {
return this.#calculator;
}
setCalculator(x: NetworkTimeCalculator.NetworkTimeCalculator): void {
if (!x || this.#calculator === x) {
return;
}
if (this.#calculator !== x) {
this.#calculator = x;
this.#columns.setCalculator(this.#calculator);
}
this.#calculator.reset();
if (this.#calculator.startAtZero) {
this.#columns.hideEventDividers();
} else {
this.#columns.showEventDividers();
}
this.#invalidateAllItems();
}
#loadEventFired(
event: Common.EventTarget
.EventTargetEvent<{resourceTreeModel: SDK.ResourceTreeModel.ResourceTreeModel, loadTime: number}>): void {
if (!this.recording) {
return;
}
const time = event.data.loadTime;
if (time) {
this.#mainRequestLoadTime = time;
this.#columns.addEventDividers([time], 'network-load-divider');
}
}
#domContentLoadedEventFired(event: Common.EventTarget.EventTargetEvent<number>): void {
if (!this.recording) {
return;
}
const {data} = event;
if (data) {
this.#mainRequestDOMContentLoadedTime = data;
this.#columns.addEventDividers([data], 'network-dcl-divider');
}
}
override wasShown(): void {
super.wasShown();
this.#refreshIfNeeded();
this.#columns.wasShown();
}
override willHide(): void {
super.willHide();
this.#columns.willHide();
}
flatNodesList(): NetworkNode[] {
const rootNode =
(this.dataGrid.rootNode() as
DataGrid.ViewportDataGrid.ViewportDataGridNode<DataGrid.SortableDataGrid.SortableDataGridNode<NetworkNode>>);
return rootNode.flatChildren() as NetworkNode[];
}
#onDataGridFocus(): void {
if (this.dataGrid.element.matches(':focus-visible') && !this.#isGridFocused) {
this.#isGridFocused = true;
this.requestUpdate();
}
this.updateNodeBackground();
}
#onDataGridBlur(): void {
if (this.#isGridFocused) {
this.#isGridFocused = false;
this.requestUpdate();
}
this.updateNodeBackground();
}
updateNodeBackground(): void {
if (this.dataGrid.selectedNode) {
(this.dataGrid.selectedNode as NetworkNode).updateBackgroundColor();
}
}
updateNodeSelectedClass(isSelected: boolean): void {
if (this.#isNodeSelected === isSelected) {
return;
}
this.#isNodeSelected = isSelected;
this.requestUpdate();
}
stylesChanged(): void {
this.#columns.scheduleRefresh();
}
#removeNodeAndMaybeAncestors(node: NetworkRequestNode): void {
let parent = node.parent;
if (!parent) {
return;
}
parent.removeChild(node);
while (parent && !parent.hasChildren() && parent.dataGrid && parent.dataGrid.rootNode() !== parent) {
const grandparent = (parent.parent as NetworkNode);
grandparent.removeChild(parent as NetworkNode);
parent = grandparent;
}
}
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private refresh(): void {
this.#needsRefresh = false;
this.removeAllNodeHighlights();
this.#timeCalculator.updateBoundariesForEventTime(this.#mainRequestLoadTime);
this.#durationCalculator.updateBoundariesForEventTime(this.#mainRequestLoadTime);
this.#timeCalculator.updateBoundariesForEventTime(this.#mainRequestDOMContentLoadedTime);
this.#durationCalculator.updateBoundariesForEventTime(this.#mainRequestDOMContentLoadedTime);
const nodesToInsert = new Map<NetworkNode, NetworkNode>();
const nodesToRefresh: NetworkNode[] = [];
const staleNodes = new Set<NetworkRequestNode>();
// While creating nodes it may add more entries into staleRequests because redirect request nodes update the parent
// node so we loop until we have no more stale requests.
while (this.staleRequests.size) {
const request = this.staleRequests.values().next().value as SDK.NetworkRequest.NetworkRequest;
this.staleRequests.delete(request);
let node = this.#networkRequestToNode.get(request);
if (!node) {
node = this.#createNodeForRequest(request);
}
staleNodes.add(node);
}
for (const node of staleNodes) {
const request = node.request();
const isFilteredOut = !this.#applyFilter(request);
if (isFilteredOut) {
if (node === this.#hoveredNode) {
this.#setHoveredNode(null);
}
node.selected = false;
} else {
nodesToRefresh.push(node);
}
this.#timeCalculator.updateBoundaries(request);
this.#durationCalculator.updateBoundaries(request);
const newParent = this.#parentNodeForInsert(node);
const wasAlreadyFiltered = filteredNetworkRequests.has(node);
if (wasAlreadyFiltered === isFilteredOut && node.parent === newParent) {
continue;
}
if (isFilteredOut) {
filteredNetworkRequests.add(node);
} else {
filteredNetworkRequests.delete(node);
}
const removeFromParent = node.parent && (isFilteredOut || node.parent !== newParent);
if (removeFromParent) {
this.#removeNodeAndMaybeAncestors(node);
}
if (!newParent || isFilteredOut) {
continue;
}
if (!newParent.dataGrid && !nodesToInsert.has(newParent)) {
nodesToInsert.set(newParent, (this.dataGrid.rootNode() as NetworkNode));
nodesToRefresh.push(newParent);
}
nodesToInsert.set(node, newParent);
}
for (const node of nodesToInsert.keys()) {
(nodesToInsert.get(node) as NetworkNode).appendChild(node);
}
for (const node of nodesToRefresh) {
node.refresh();
}
this.#updateSummaryBar();
if (nodesToInsert.size) {
this.#columns.sortByCurrentColumn();
}
this.dataGrid.updateInstantly();
this.didRefreshForTest();
}
// Accessed in web_tests / legacy_test_runner.
private didRefreshForTest(): void {
}
#parentNodeForInsert(node: NetworkRequestNode): NetworkNode|null {
if (!this.#activeGroupLookup) {
return this.dataGrid.rootNode() as NetworkNode;
}
const groupNode = this.#activeGroupLookup.groupNodeForRequest(node.request());
if (!groupNode) {
return this.dataGrid.rootNode() as NetworkNode;
}
return groupNode;
}
// Accessed in web_tests / legacy_test_runner.
// eslint-disable-next-line @devtools/prefer-private-class-members
private reset(): void {
this.dispatchEventToListeners(Events.RequestActivated, {showPanel: RequestPanelBehavior.HidePanel});
this.dispatchEventToListeners(Events.RequestSelected, null);
this.#setHoveredNode(null);
this.#columns.reset();
this.#timeFilter = null;
this.#calculator.reset();
this.#timeCalculator.setWindow(null);
this.#linkifier.reset();
if (this.#activeGroupLookup) {
this.#activeGroupLookup.reset();
}
this.staleRequests.clear();
this.#resetSuggestionBuilder();
this.#mainRequestLoadTime = -1;
this.#mainRequestDOMContentLoadedTime = -1;
this.#networkRequestToNode = new WeakMap();
this.dataGrid.rootNode().removeChildren();
this.#updateSummaryBar();
this.scheduleRefresh();
}
setTextFilterValue(filterString: string): void {
this.#textFilterUI.setValue(filterString);
this.#networkHideDataURLSetting.set(false);
this.#networkShowBlockedCookiesOnlySetting.set(false);
this.#networkOnlyBlockedRequestsSetting.set(false);
this.#networkOnlyThirdPartySetting.set(false);
this.#networkHideChromeExtensions.set(false);
this.resourceCategoryFilterUI.reset();
}
#createNodeForRequest(request: SDK.NetworkRequest.NetworkRequest): NetworkRequestNode {
const node = new NetworkRequestNode(this, request);
this.#networkRequestToNode.set(request, node);
filteredNetworkRequests.add(node);
for (let redirect = request.redirectSource(); redirect; redirect = redirect.redirectSource()) {
this.#refreshRequest(redirect);
}
return node;
}
#isInScope(request: SDK.NetworkRequest.NetworkRequest): boolean {
const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request);
return !networkManager || SDK.TargetManager.TargetManager.instance().isInScope(networkManager);
}
#onRequestUpdated(event: Common.EventTarget
.EventTargetEvent<{request: SDK.NetworkRequest.NetworkRequest, preserveLog?: boolean}>): void {
const {request, preserveLog} = event.data;
if (this.#isInScope(request) || preserveLog) {
this.#refreshRequest(request);
}
}
#onRequestRemoved(event: Common.EventTarget.EventTargetEvent<{request: SDK.NetworkRequest.NetworkRequest}>): void {
const {request} = event.data;
this.staleRequests.delete(request);
const node = this.#networkRequestToNode.get(request);
if (node) {
this.#removeNodeAndMaybeAncestors(node);
}
}
#refreshRequest(request: SDK.NetworkRequest.NetworkRequest): void {
NetworkLogView.subdomains(request.domain)
.forEach(
this.#suggestionBuilder.addItem.bind(this.#suggestionBuilder, NetworkForward.UIFilter.FilterType.Domain));
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Method, request.requestMethod);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.MimeType, request.mimeType);
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Scheme, String(request.scheme));
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.StatusCode, String(request.statusCode));
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.ResourceType, request.resourceType().name());
const requestURLSecurityOrigin = request.requestURLSecurityOrigin();
if (!requestURLSecurityOrigin.isOpaque()) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Url, requestURLSecurityOrigin.siteId());
}
const priority = request.priority();
if (priority) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.Priority,
PerfUI.NetworkPriorities.uiLabelForNetworkPriority(priority));
}
if (request.mixedContentType !== Protocol.Security.MixedContentType.None) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.MixedContent,
NetworkForward.UIFilter.MixedContentFilterValues.ALL);
}
if (request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.MixedContent,
NetworkForward.UIFilter.MixedContentFilterValues.DISPLAYED);
}
if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable) {
const suggestion = request.wasBlocked() ? NetworkForward.UIFilter.MixedContentFilterValues.BLOCKED :
NetworkForward.UIFilter.MixedContentFilterValues.BLOCK_OVERRIDDEN;
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.MixedContent, suggestion);
}
const responseHeaders = request.responseHeaders;
for (const responseHeader of responseHeaders) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasResponseHeader, responseHeader.name);
if (responseHeader.name === 'Set-Cookie') {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.ResponseHeaderValueSetCookie);
}
}
for (const header of request.requestHeaders()) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.HasRequestHeader, header.name);
}
for (const cookie of request.responseCookies) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.SetCookieDomain, cookie.domain());
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.SetCookieName, cookie.name());
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.SetCookieValue, cookie.value());
}
for (const cookie of request.allCookiesIncludingBlockedOnes()) {
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.CookieDomain, cookie.domain());
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.CookieName, cookie.name());
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.CookiePath, cookie.path());
this.#suggestionBuilder.addItem(NetworkForward.UIFilter.FilterType.CookieValue, cookie.value());
}
this.staleRequests.add(request);
this.scheduleRefresh();
}
rowHeight(): number {
return this.#rowHeight;
}
switchViewMode(gridMode: boolean): void {
this.#columns.switchViewMode(gridMode);
}
handleContextMenuForRequest(contextMenu: UI.ContextMenu.ContextMenu, request: SDK.NetworkRequest.NetworkRequest):
void {
contextMenu.appendApplicableItems(request);
const filtered = this.#filterBar.hasActiveFilter();
const copyMenu = contextMenu.clipboardSection().appendSubMenuItem(i18nString(UIStrings.copy), false, 'copy');
if (request) {
const openAiAssistanceId = 'drjones.network-panel-context';
if (UI.ActionRegistry.ActionRegistry.instance().hasAction(openAiAssistanceId)) {
UI.Context.Context.instance().setFlavor(SDK.NetworkRequest.NetworkRequest, request);
contextMenu.footerSection().appendAction(openAiAssistanceId);
}
copyMenu.defaultSection().appendItem(
i18nString(UIStrings.copyURL),
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText.bind(
Host.InspectorFrontendHost.InspectorFrontendHostInstance, request.contentURL()),
{jslogContext: 'copy-url'});
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedURLs) : i18nString(UIStrings.copyAllURLs),
this.#copyAllURLs.bind(this), {jslogContext: 'copy-all-urls'});
if (request.requestHeadersText()) {
copyMenu.saveSection().appendItem(i18nString(UIStrings.copyRequestHeaders),
NetworkLogView.#copyRequestHeaders.bind(null, request),
{jslogContext: 'copy-request-headers'});
}
if (request.responseHeadersText) {
copyMenu.saveSection().appendItem(i18nString(UIStrings.copyResponseHeaders),
NetworkLogView.#copyResponseHeaders.bind(null, request),
{jslogContext: 'copy-response-headers'});
}
if (request.finished) {
copyMenu.saveSection().appendItem(i18nString(UIStrings.copyResponse),
NetworkLogView.#copyResponse.bind(null, request),
{jslogContext: 'copy-response'});
}
const initiator = request.initiator();
if (initiator) {
const stack = initiator.stack;
if (stack) {
// We proactively compute the stacktrace text, as we can't determine whether the stacktrace
// has any context solely based on the top frame. Sometimes, the top frame does not have
// any callFrames, but its parent frames do.
const stackTraceText = computeStackTraceText(stack);
if (stackTraceText !== '') {
copyMenu.saveSection().appendItem(i18nString(UIStrings.copyStacktrace), () => {
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(stackTraceText);
}, {jslogContext: 'copy-stacktrace'});
}
}
}
const disableIfBlob = request.isBlobRequest();
if (Host.Platform.isWin()) {
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsCurlCmd),
this.#copyCurlCommand.bind(this, request, 'win'),
{disabled: disableIfBlob, jslogContext: 'copy-as-curl-cmd'});
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsCurlBash),
this.#copyCurlCommand.bind(this, request, 'unix'),
{disabled: disableIfBlob, jslogContext: 'copy-as-curl-bash'});
} else {
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsCurl),
this.#copyCurlCommand.bind(this, request, 'unix'),
{disabled: disableIfBlob, jslogContext: 'copy-as-curl'});
}
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsPowershell),
this.#copyPowerShellCommand.bind(this, request),
{disabled: disableIfBlob, jslogContext: 'copy-as-powershell'});
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsFetch),
this.#copyFetchCall.bind(this, request, FetchStyle.BROWSER),
{disabled: disableIfBlob, jslogContext: 'copy-as-fetch'});
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsNodejsFetch),
this.#copyFetchCall.bind(this, request, FetchStyle.NODE_JS),
{disabled: disableIfBlob, jslogContext: 'copy-as-nodejs-fetch'});
this.#appendCopyAsPreloadItem(copyMenu, request);
if (Host.Platform.isWin()) {
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsCurlCmd) : i18nString(UIStrings.copyAllAsCurlCmd),
this.#copyAllCurlCommand.bind(this, 'win'), {jslogContext: 'copy-all-as-curl-cmd'});
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsCurlBash) : i18nString(UIStrings.copyAllAsCurlBash),
this.#copyAllCurlCommand.bind(this, 'unix'), {jslogContext: 'copy-all-as-curl-bash'});
} else {
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsCurl) : i18nString(UIStrings.copyAllAsCurl),
this.#copyAllCurlCommand.bind(this, 'unix'), {jslogContext: 'copy-all-as-curl'});
}
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsPowershell) : i18nString(UIStrings.copyAllAsPowershell),
this.#copyAllPowerShellCommand.bind(this), {jslogContext: 'copy-all-as-powershell'});
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsFetch) : i18nString(UIStrings.copyAllAsFetch),
this.#copyAllFetchCall.bind(this, FetchStyle.BROWSER), {jslogContext: 'copy-all-as-fetch'});
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsNodejsFetch) : i18nString(UIStrings.copyAllAsNodejsFetch),
this.#copyAllFetchCall.bind(this, FetchStyle.NODE_JS), {jslogContext: 'copy-all-as-nodejs-fetch'});
}
copyMenu.footerSection().appendItem(
filtered ? i18nString(UIStrings.copyAllListedAsHarSanitized) : i18nString(UIStrings.copyAllAsHarSanitized),
this.#copyAllAsHAR.bind(this, {sanitize: true}), {jslogContext: 'copy-all-as-har'});
if (this.#networkShowOptionsToGenerateHarWithSensitiveData.get()) {
copyMenu.footerSection().appendItem(filtered ? i18nString(UIStrings.copyAllListedAsHarWithSensitiveData) :
i18nString(UIStrings.copyAllAsHarWithSensitiveData),
this.#copyAllAsHAR.bind(this, {sanitize: false}),
{jslogContext: 'copy-all-as-har-with-sensitive-data'});
}
contextMenu.overrideSection().appendItem(
i18nString(UIStrings.overrideHeaders), this.#handleCreateResponseHeaderOverrideClick.bind(this, request), {
disabled:
Persistence.NetworkPersistenceManager.NetworkPersistenceManager.isForbiddenNetworkUrl(request.url()),
jslogContext: 'override-headers',
});
contextMenu.editSection().appendItem(i18nString(UIStrings.clearBrowserCache), this.#clearBrowserCache.bind(this),
{jslogContext: 'clear-browser-cache'});
contextMenu.editSection().appendItem(i18nString(UIStrings.clearBrowserCookies),
this.#clearBrowserCookies.bind(this), {jslogContext: 'clear-browser-cookies'});
if (request) {
const maxBlockedURLLength = 20;
const manager = SDK.NetworkManager.MultitargetNetworkManager.instance();
function removeRequestCondition(pattern: SDK.NetworkManager.RequestURLPattern): void {
const entry = manager.requestConditions.findCondition(pattern.constructorString);
if (entry) {
manager.requestConditions.delete(entry);
void UI.ViewManager.ViewManager.instance().showView('network.blocked-urls');
}
}
function addRequestCondition(
pattern: SDK.NetworkManager.RequestURLPattern,
conditions: SDK.NetworkManager.ThrottlingConditions,
): void {
const entry = manager.requestConditions.findCondition(pattern.constructorString);
if (entry) {
entry.conditions = conditions;
} else {
manager.requestConditions.add(SDK.NetworkManager.RequestCondition.create(pattern, conditions));
}
manager.requestConditions.conditionsEnabled = true;
void UI.ViewManager.ViewManager.instance().showView('network.blocked-urls');
}
const blockingMenu =
contextMenu.debugSection().appendSubMenuItem(i18nString(UIStrings.blockRequests), /* disabled=*/ true);
const throttlingMenu =
contextMenu.debugSection().appendSubMenuItem(i18nString(UIStrings.throttleRequests), /* disabled=*/ true);
const parsed = request.parsedURL;
let urlPatternString = '';
if (parsed.isValid) {
// We cannot escape parsed.urlWithoutScheme() directly. If we escaped the first '?'
// URLPattern would treat the entire string as the pathname and fail to match the query string.
// Thus, we must escape the components individually and reconstruct the pattern string.
urlPatternString = '*://' + Platform.StringUtilities.escapeForURLPattern(parsed.host);
if (parsed.port) {
urlPatternString += ':' + Platform.StringUtilities.escapeForURLPattern(parsed.port);
}
urlPatternString += Platform.StringUtilities.escapeForURLPattern(parsed.path);
if (parsed.queryParams) {
urlPatternString += '?' + Platform.StringUtilities.escapeForURLPattern(parsed.queryParams);
}
if (parsed.fragment) {
urlPatternString += '#' + Platform.StringUtilities.escapeForURLPattern(parsed.fragment);
}
} else if (parsed.urlWithoutScheme()) {
urlPatternString = '*://' + Platform.StringUtilities.escapeForURLPattern(parsed.urlWithoutScheme());
}
const urlPattern = urlPatternString &&
SDK.NetworkManager.RequestURLPattern.create(
urlPatternString as SDK.NetworkManager.URLPatternConstructorString);
if (urlPattern) {
throttlingMenu.setEnabled(true);
blockingMenu.setEnabled(true);
const existingConditions = manager.requestConditions.findCondition(urlPattern.constructorString);
const isBlocking = existingConditions?.conditions === SDK.NetworkManager.BlockingConditions;
const isThrottling = existingConditions &&
existingConditions.conditions !== SDK.NetworkManager.BlockingConditions &&
existingConditions.conditions !== SDK.NetworkManager.NoThrottlingConditions;
const croppedURL = Platform.StringUtilities.trimMiddle(urlPattern.constructorString, maxBlockedURLLength);
blockingMenu.debugSection().appendItem(
isBlocking ? i18nString(UIStrings.unblockS, {PH1: croppedURL}) : i18nString(UIStrings.blockRequestUrl),
() => isBlocking ? removeRequestCondition(urlPattern) :
addRequestCondition(urlPattern, SDK.NetworkManager.BlockingConditions),
{jslogContext: 'block-request-url'});
throttlingMenu.debugSection().appendItem(
isThrottling ? i18nString(UIStrings.unthrottleS, {PH1: croppedURL}) :
i18nString(UIStrings.throttleRequestUrl),
() => isThrottling ? removeRequestCondition(urlPattern) :
addRequestCondition(urlPattern, SDK.NetworkManager.Slow3GConditions),
{jslogContext: 'throttle-request-url'});
}
let domainPatternString = '';
if (parsed.isValid) {
domainPatternString = '*://' + Platform.StringUtilities.escapeForURLPattern(parsed.host);
if (parsed.port) {
domainPatternString += ':' + Platform.StringUtilities.escapeForURLPattern(parsed.port);
}
} else if (parsed.domain()) {
domainPatternString = '*://' + Platform.StringUtilities.escapeForURLPattern(parsed.domain());
}
const domainPattern = domainPatternString &&
SDK.NetworkManager.RequestURLPattern.create(
domainPatternString as SDK.NetworkManager.URLPatternConstructorString);
if (domainPattern) {
throttlingMenu.setEnabled(true);
blockingMenu.setEnabled(true);
const existingConditions = manager.requestConditions.findCondition(domainPattern.constructorString);
const isBlocking = existingConditions?.conditions === SDK.NetworkManager.BlockingConditions;
const isThrottling = existingConditions &&
existingConditions.conditions !== SDK.NetworkManager.BlockingConditions &&
existingConditions.conditions !== SDK.NetworkManager.NoThrottlingConditions;
const croppedURL = Platform.StringUtilities.trimMiddle(domainPattern.constructorString, maxBlockedURLLength);
blockingMenu.debugSection().appendItem(
isBlocking ? i18nString(UIStrings.unblockS, {PH1: croppedURL}) : i18nString(UIStrings.blockRequestDomain),
() => isBlocking ? removeRequestCondition(domainPattern) :
addRequestCondition(domainPattern, SDK.NetworkManager.BlockingConditions),
{jslogContext: 'block-request-domain'});
throttlingMenu.debugSection().appendItem(
isThrottling ? i18nString(UIStrings.unthrottleS, {PH1: croppedURL}) :
i18nString(UIStrings.throttleRequestDomain),
() => isThrottling ? removeRequestCondition(domainPattern) :
addRequestCondition(domainPattern, SDK.NetworkManager.Slow3GConditions),
{jslogContext: 'throttle-request-domain'});
}
if (SDK.NetworkManager.NetworkManager.canResendRequest(request, true)) {
contextMenu.debugSection().appendItem(i18nString(UIStrings.resend),
SDK.NetworkManager.NetworkManager.replayRequest.bind(null, request),
{jslogContext: 'resend'});
}
if (SDK.NetworkManager.NetworkManager.canResendRequest(request, false)) {
contextMenu.debugSection().appendItem(i18nString(UIStrings.editAndResendAsFetch),
this.#resendFromConsole.bind(this, request),
{jslogContext: 'edit-and-resend-as-fetch'});
}
}
}
#harRequests(): SDK.NetworkRequest.NetworkRequest[] {
const requests = Logs.NetworkLog.NetworkLog.instance().requests().filter(request => this.#applyFilter(request));
return requests.filter(NetworkLogView.getHTTPRequestsFilter).filter(request => {
return request.finished ||
(request.resourceType() === Common.ResourceType.resourceTypes.WebSocket && request.responseReceivedTime) ||
Boolean(request.eventSourceMessages()?.length);
});
}
async #copyAllAsHAR(options: HAR.Log.BuildOptions): Promise<void> {
const harArchive = {log: await HAR.Log.Log.build(this.#harRequests(), options)};
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(JSON.stringify(harArchive, null, 2));
}
#copyAllURLs(): void {
const requests = Logs.NetworkLog.NetworkLog.instance().requests().filter(request => this.#applyFilter(request));
const nonBlobRequests = this.#filterOutBlobRequests(requests);
const urls = nonBlobRequests.map(request => request.url());
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(urls.join('\n'));
}
async #copyCurlCommand(request: SDK.NetworkRequest.NetworkRequest, platform: 'unix'|'win'): Promise<void> {
const command = await NetworkLogView.generateCurlCommand(request, platform);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);
}
async #copyAllCurlCommand(platform: 'unix'|'win'): Promise<void> {
const requests = Logs.NetworkLog.NetworkLog.instance().requests().filter(request => this.#applyFilter(request));
const commands = await this.#generateAllCurlCommand(requests, platform);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);
}
#copyPreloadElement(request: SDK.NetworkRequest.NetworkRequest): void {
const preloadLink = generatePreloadLink(request);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(preloadLink);
}
#appendCopyAsPreloadItem(copyMenu: UI.ContextMenu.SubMenu, request: SDK.NetworkRequest.NetworkRequest): void {
const isHttpOrHttps = request.parsedURL.scheme === 'http' || request.parsedURL.scheme === 'https';
const isGetRequest = request.requestMethod === 'GET';
const networkManager = SDK.NetworkManager.NetworkManager.forRequest(request);
const resourceTreeModel = networkManager?.target().model(SDK.ResourceTreeModel.ResourceTreeModel);
const isMainDocument = Boolean(resourceTreeModel?.mainFrame && resourceTreeModel.mainFrame.id === request.frameId &&
request.resourceType() === Common.ResourceType.resourceTypes.Document);
const disablePreload =
!isHttpOrHttps || request.isBlobRequest() || !isGetRequest || isMainDocument || !canPreloadRequest(request);
copyMenu.defaultSection().appendItem(i18nString(UIStrings.copyAsPreload),
this.#copyPreloadElement.bind(this, request),
{disabled: disablePreload, jslogContext: 'copy-as-preload'});
}
async #copyFetchCall(request: SDK.NetworkRequest.NetworkRequest, style: FetchStyle): Promise<void> {
const command = await this.#generateFetchCall(request, style);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);
}
async #copyAllFetchCall(style: FetchStyle): Promise<void> {
const requests = Logs.NetworkLog.NetworkLog.instance().requests().filter(request => this.#applyFilter(request));
const commands = await this.#generateAllFetchCall(requests, style);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);
}
async #resendFromConsole(request: SDK.NetworkRequest.NetworkRequest): Promise<void> {
// Record telemetry
Host.userMetrics.editResendRequest(Host.UserMetrics.resendRequestType(request.resourceType()));
// Step 1: Generate an editable fetch command that retains forbidden headers as comments.
let fetchCommand = await this.#generateFetchCall(request, FetchStyle.BROWSER, {commentForbiddenHeaders: true});
// Step 2: Prepend 'await' unless already present
if (!fetchCommand.startsWith('await ')) {
fetchCommand = 'await ' + fetchCommand;
}
// Prepend execution context guidance comments
const contextDescription = NetworkRequestNode.getExecutionContextDescription(request);
if (contextDescription) {
const contextComments = i18nString(UIStrings.originallyCalledFromContext, {PH1: contextDescription}) + '\n' +
i18nString(UIStrings.selectExecutionContextInConsole) + '\n';
fetchCommand = contextComments + fetchCommand;
}
// Append invitation to edit before resending
fetchCommand += '\n' + i18nString(UIStrings.editAndEnterToResend);
// Step 3: Show the console drawer (without switching away from network panel)
UI.InspectorView.InspectorView.instance().showDrawer({focus: false, hasTargetDrawer: true});
void UI.ViewManager.ViewManager.instance().showView('console-view', /* userGesture */ false, /* omitFocus */ true);
// Step 4: Log console message with link to original request
NetworkLogView.#logResendConsoleMessage(request);
// Step 5: Inject fetch command into console prompt
const consoleViewWrapper = await UI.ViewManager.ViewManager.instance().view('console-view');
if (!consoleViewWrapper) {
return;
}
const widget = await consoleViewWrapper.widget();
// Use a minimal interface to avoid circular imports
interface ConsoleViewWithPrompt {
insertIntoPrompt(text: string): void;
}
const consoleView = widget as unknown as Partial<ConsoleViewWithPrompt>;
if (typeof consoleView.insertIntoPrompt !== 'function') {
return;
}
consoleView.insertIntoPrompt(fetchCommand);
}
static #logResendConsoleMessage(request: SDK.NetworkRequest.NetworkRequest): void {
const target = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
if (!target) {
return;
}
const runtimeModel = target.model(SDK.RuntimeModel.RuntimeModel);
const consoleModel = target.model(SDK.ConsoleModel.ConsoleModel);
if (!runtimeModel || !consoleModel) {
return;
}
const method = request.requestMethod;
const name = request.name();
const logMessage = i18nString(UIStrings.resendableCopyOfRequest, {PH1: method, PH2: name});
const requestId = request.requestId();
const message = new SDK.ConsoleModel.ConsoleMessage(
runtimeModel, Protocol.Log.LogEntrySource.Network, Protocol.Log.LogEntryLevel.Info, logMessage, {
affectedResources: {requestId: requestId as Protocol.Network.RequestId},
});
consoleModel.addMessage(message);
// Associate message with request for bidirectional linking
Logs.NetworkLog.NetworkLog.instance().associateConsoleMessageWithRequest(message, requestId);
// Clear the initiator-derived fields to prevent confusing "VM123:1" display
message.url = undefined;
message.line = 0;
message.column = 0;
message.stackTrace = undefined;
}
async #copyPowerShellCommand(request: SDK.NetworkRequest.NetworkRequest): Promise<void> {
const command = await this.#generatePowerShellCommand(request);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(command);
}
async #copyAllPowerShellCommand(): Promise<void> {
const requests = Logs.NetworkLog.NetworkLog.instance().requests().filter(request => this.#applyFilter(request));
const commands = await this.#generateAllPowerShellCommand(requests);
Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(commands);
}
async exportAll(options: HAR.Log.BuildOptions): Promise<void> {
const mainTarget = SDK.TargetManager.TargetManager.instance().scopeTarget();
if (!mainTarget) {
return;
}
const url = mainTarget.inspectedURL();
const parsedURL = Common.ParsedURL.ParsedURL.fromString(url);
const filename = (parsedURL ? parsedURL.host : 'network-log') as Platform.DevToolsPath.RawPathString;
const stream = new Bindings.FileUtils.FileOutputStream(Workspace.FileManager.FileManager.instance());
if (!await stream.open(Common.ParsedURL.ParsedURL.concatenate(filename, '.har'))) {
return;
}
const progressIndicator = this.#progressBarContainer.createChild('devtools-progress');
await HAR.Writer.Writer.write(stream, this.#harRequests(), options, progressIndicator);
progressIndicator.done = true;
void stream.close();
}
async #handleCreateResponseHeaderOverrideClick(request: SDK.NetworkRequest.NetworkRequest): Promise<void> {
const requestLocation =
NetworkForward.UIRequestLocation.UIRequestLocation.responseHeaderMatch(request, {name: '', value: ''});
const networkPersistenceManager = Persistence.NetworkPersistenceManager.NetworkPersistenceManager.instance();
if (networkPersistenceManager.project()) {
Common.Settings.Settings.instance()
.resolve(Persistence.NetworkPersistenceManager.persistenceNetworkOverridesEnabledSettingDescriptor)
.set(true);
await networkPersistenceManager.getOrCreateHeadersUISourceCodeFromUrl(request.url());
await Common.Revealer.reveal(requestLocation);
} else { // If folder for local overrides has not been provided yet
UI.InspectorView.InspectorView.instance().displaySelectOverrideFolderInfobar(async () => {
await Sources.SourcesNavigator.OverridesNavigatorView.setupNewWorkspace();
await networkPersistenceManager.getOrCreateHeadersUISourceCodeFromUrl(request.url());
await Common.Revealer.reveal(requestLocation);
});
}
}
#clearBrowserCache(): void {
if (confirm(i18nString(UIStrings.areYouSureYouWantToClearBrowser))) {
SDK.NetworkManager.MultitargetNetworkManager.instance().clearBrowserCache();
}
}
#clearBrowserCookies(): void {
if (confirm(i18nString(UIStrings.areYouSureYouWantToClearBrowserCookies))) {
SDK.NetworkManager.MultitargetNetworkManager.instance().clearBrowserCookies();
}
}
#applyFilter(request: SDK.NetworkRequest.NetworkRequest): boolean {
if (this.#timeFilter && !this.#timeFilter(request)) {
return false;
}
const categoryName = request.resourceType().category().name;
if (!this.resourceCategoryFilterUI.accept(categoryName)) {
return false;
}
const [hideDataURL, blockedCookies, blockedRequests, thirdParty, hideExtensionURL] = [
this.#networkHideDataURLSetting.get(),
this.#networkShowBlockedCookiesOnlySetting.get(),
this.#networkOnlyBlockedRequestsSetting.get(),
this.#networkOnlyThirdPartySetting.get(),
this.#networkHideChromeExtensions.get(),
];
if (hideDataURL && (request.parsedURL.isDataURL() || request.parsedURL.isBlobURL())) {
return false;
}
if (blockedCookies && !request.blockedResponseCookies().length) {
return false;
}
if (blockedRequests && !request.wasBlocked() && !request.corsErrorStatus()) {
return false;
}
if (thirdParty && request.isSameSite()) {
return false;
}
if (hideExtensionURL && request.scheme === 'chrome-extension') {
return false;
}
for (let i = 0; i < this.#filters.length; ++i) {
if (!this.#filters[i](request)) {
return false;
}
}
return true;
}
#isValidUrl(url: string): boolean {
try {
new URL(url);
return true;
} catch {
return false;
}
}
#parseFilterQuery(query: string, invert: boolean): void {
// A query string can have multiple filters, some of them regular
// expressions, some not. Each one of those filters can be negated with a
// "-" prefix, including the regular expressions. The top-level `invert`
// checkbox therefore inverts each one of those individual filters.
const descriptors = this.#filterParser.parse(query);
this.#filters = descriptors.map(descriptor => {
const key = descriptor.key;
const text = descriptor.text || '';
const regex = descriptor.regex;
let filter;
if (key) {
const defaultText = Platform.StringUtilities.escapeForRegExp(key + ':' + text);
filter = this.#createSpecialFilter((key as NetworkForward.UIFilter.FilterType), text) ||
NetworkLogView.#requestHostAndPathFilter.bind(null, new RegExp(defaultText, 'i'));
} else if (descriptor.regex) {
filter = NetworkLogView.#requestHostAndPathFilter.bind(null, (regex as RegExp));
} else if (this.#isValidUrl(text)) {
filter = NetworkLogView.#requestUrlFilter.bind(null, text);
} else {
filter = NetworkLogView.#requestHostAndPathFilter.bind(
null, new RegExp(Platform.StringUtilities.escapeForRegExp(text), 'i'));
}
if ((descriptor.negative && !invert) || (!descriptor.negative && invert)) {
return NetworkLogView.#negativeFilter.bind(null, filter);
}
return filter;
});
}
#createSpecialFilter(type: NetworkForward.UIFilter.FilterType, value: string): Filter|null {
switch (type) {
case NetworkForward.UIFilter.FilterType.Domain:
return NetworkLogView.createRequestDomainFilter(value);
case NetworkForward.UIFilter.FilterType.HasResponseHeader:
return NetworkLogView.#requestResponseHeaderFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.ResponseHeaderValueSetCookie:
return NetworkLogView.#requestResponseHeaderSetCookieFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.HasRequestHeader:
return NetworkLogView.#requestRequestHeaderFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.Is:
if (value.toLowerCase() === NetworkForward.UIFilter.IsFilterType.RUNNING) {
return NetworkLogView.#runningRequestFilter;
}
if (value.toLowerCase() === NetworkForward.UIFilter.IsFilterType.FROM_CACHE) {
return NetworkLogView.#fromCacheRequestFilter;
}
if (value.toLowerCase() === NetworkForward.UIFilter.IsFilterType.SERVICE_WORKER_INTERCEPTED) {
return NetworkLogView.#interceptedByServiceWorkerFilter;
}
if (value.toLowerCase() === NetworkForward.UIFilter.IsFilterType.SERVICE_WORKER_INITIATED) {
return NetworkLogView.#initiatedByServiceWorkerFilter;
}
if (value.toLowerCase() === NetworkForward.UIFilter.IsFilterType.PRELOAD) {
return NetworkLogView.#linkPreloadRequestFilter;
}
break;
case NetworkForward.UIFilter.FilterType.LargerThan:
return this.#createSizeFilter(value.toLowerCase());
case NetworkForward.UIFilter.FilterType.Method:
return NetworkLogView.#requestMethodFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.MimeType:
return NetworkLogView.#requestMimeTypeFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.MixedContent:
return NetworkLogView.#requestMixedContentFilter.bind(
null, (value as NetworkForward.UIFilter.MixedContentFilterValues));
case NetworkForward.UIFilter.FilterType.Scheme:
return NetworkLogView.#requestSchemeFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.SetCookieDomain:
return NetworkLogView.#requestSetCookieDomainFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.SetCookieName:
return NetworkLogView.#requestSetCookieNameFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.SetCookieValue:
return NetworkLogView.#requestSetCookieValueFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.CookieDomain:
return NetworkLogView.#requestCookieDomainFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.CookieName:
return NetworkLogView.#requestCookieNameFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.CookiePath:
return NetworkLogView.#requestCookiePathFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.CookieValue:
return NetworkLogView.#requestCookieValueFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.Priority:
return NetworkLogView.#requestPriorityFilter.bind(null,
PerfUI.NetworkPriorities.uiLabelToNetworkPriority(value));
case NetworkForward.UIFilter.FilterType.StatusCode:
return NetworkLogView.#statusCodeFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.HasOverrides:
return NetworkLogView.#hasOverridesFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.ResourceType:
return NetworkLogView.#resourceTypeFilter.bind(null, value);
case NetworkForward.UIFilter.FilterType.Url:
return NetworkLogView.#requestUrlFilter.bind(null, value);
}
return null;
}
#createSizeFilter(value: string): Filter|null {
let multiplier = 1;
if (value.endsWith('k')) {
multiplier = 1000;
value = value.substring(0, value.length - 1);
} else if (value.endsWith('m')) {
multiplier = 1000 * 1000;
value = value.substring(0, value.length - 1);
}
const quantity = Number(value);
if (isNaN(quantity)) {
return null;
}
return NetworkLogView.#requestSizeLargerThanFilter.bind(null, quantity * multiplier);
}
#filterRequests(): void {
this.removeAllNodeHighlights();
this.#invalidateAllItems();
}
#reveal(request: SDK.NetworkRequest.NetworkRequest): NetworkRequestNode|null {
this.removeAllNodeHighlights();
const node = this.#networkRequestToNode.get(request);
if (!node?.dataGrid) {
return null;
}
// Viewport datagrid nodes do not reveal if not in the root node
// list of flatChildren. For children of grouped frame nodes:
// reveal and expand parent to ensure child is revealable.
if (node.parent && node.parent instanceof NetworkGroupNode) {
node.parent.reveal();
node.parent.expand();
}
node.reveal();
return node;
}
revealAndHighlightRequest(request: SDK.NetworkRequest.NetworkRequest): void {
const node = this.#reveal(request);
if (node) {
this.#highlightNode(node);
}
}
revealAndHighlightRequestWithId(requestId: NetworkForward.NetworkRequestId.NetworkRequestId): void {
const request = Logs.NetworkLog.NetworkLog.instance().requestByManagerAndId(requestId.manager, requestId.requestId);
if (request) {
this.revealAndHighlightRequest(request);
}
}
selectRequest(request: SDK.NetworkRequest.NetworkRequest, options?: NetworkForward.UIRequestLocation.FilterOptions):
void {
const defaultOptions = {clearFilter: true};
const {clearFilter} = options || defaultOptions;
if (clearFilter) {
this.setTextFilterValue('');
}
const node = this.#reveal(request);
if (node) {
node.select();
}
}
removeAllNodeHighlights(): void {
if (this.#highlightedNode) {
this.#highlightedNode.element().classList.remove('highlighted-row');
this.#highlightedNode = null;
}
}
#highlightNode(node: NetworkRequestNode): void {
UI.UIUtils.runCSSAnimationOnce(node.element(), 'highlighted-row');
this.#highlightedNode = node;
}
#filterOutBlobRequests(requests: SDK.NetworkRequest.NetworkRequest[]): SDK.NetworkRequest.NetworkRequest[] {
return requests.filter(request => !request.isBlobRequest());
}
static #getValidClipboardUrl(url: Platform.DevToolsPath.UrlString): Platform.DevToolsPath.UrlString|null {
// `hasWebSafeScheme` unwraps `blob:` and `filesystem:` URLs to check their inner origin,
// but standalone CLI tools (cURL, PowerShell, fetch) cannot request browser-internal URLs.
if (Common.ParsedURL.schemeIs(url, 'blob:') || Common.ParsedURL.schemeIs(url, 'filesystem:') ||
!Common.ParsedURL.hasWebSafeScheme(url)) {
return null;
}
return url;
}
async #generateFetchCall(request: SDK.NetworkRequest.NetworkRequest, style: FetchStyle,
generateOptions?: {commentForbiddenHeaders?: boolean}): Promise<string> {
// Editable fetch commands retain unsafe headers so the generated output can
// show them as comments, but still omit protocol-internal pseudo-headers.
const internalOnly = new Set<string>(['method', 'path', 'scheme', 'version']);
const shouldFilterHeader = (name: string, value: string): boolean => {
const lowerName = name.toLowerCase();
if (internalOnly.has(lowerName) || name.includes(':')) {
return true;
}
if (generateOptions?.commentForbiddenHeaders) {
return false;
}
// TODO(phistuck) - remove this once crbug.com/571722 is fixed.
return lowerName === 'user-agent' || isForbiddenHeader(name, value);
};
const credentialHeaders = new Set<string>(['cookie', 'authorization']);
const validUrl = NetworkLogView.#getValidClipboardUrl(request.url());
if (!validUrl) {
return i18nString(UIStrings.unsupportedUrlScheme, {PH1: '//'});
}
const url = JSON.stringify(validUrl);
const requestHeaders = request.requestHeaders();
const headerData: Headers = requestHeaders.reduce((result, header) => {
const name = header.name;
if (!shouldFilterHeader(name, header.value)) {
result.append(name, header.value);
}
return result;
}, new Headers());
const headers: HeadersInit = {};
for (const headerArray of headerData) {
headers[headerArray[0]] = headerArray[1];
}
const credentials = request.includedRequestCookies().length ||
requestHeaders.some(({name}) => credentialHeaders.has(name.toLowerCase())) ?
'include' :
'omit';
const referrerHeader = requestHeaders.find(({name}) => name.toLowerCase() === 'referer');
const referrer = referrerHeader ? referrerHeader.value : void 0;
const requestBody = await request.requestFormData();
const fetchOptions: RequestInit = {
headers: Object.keys(headers).length ? headers : void 0,
referrer,
body: requestBody,
method: request.requestMethod,
mode: 'cors',
};
if (style === FetchStyle.NODE_JS) {
const cookieHeader = requestHeaders.find(header => header.name.toLowerCase() === 'cookie');
const extraHeaders: HeadersInit = {};
// According to https://www.npmjs.com/package/node-fetch#class-request the
// following properties are not implemented in Node.js.
delete fetchOptions.mode;
if (cookieHeader) {
extraHeaders['cookie'] = cookieHeader.value;
}
if (referrer) {
delete fetchOptions.referrer;
extraHeaders['Referer'] = referrer;
}
if (Object.keys(extraHeaders).length) {
fetchOptions.headers = {
...headers,
...extraHeaders,
};
}
} else {
fetchOptions.credentials = credentials;
}
let options = JSON.stringify(fetchOptions, null, 2);
if (generateOptions?.commentForbiddenHeaders) {
options = commentForbiddenHeaders(options);
}
return `fetch(${url}, ${options});`;
}
async #generateAllFetchCall(requests: SDK.NetworkRequest.NetworkRequest[], style: FetchStyle): Promise<string> {
const nonBlobRequests = this.#filterOutBlobRequests(requests);
const commands = await Promise.all(nonBlobRequests.map(request => this.#generateFetchCall(request, style)));
return commands.join(' ;\n');
}
static async generateCurlCommand(request: SDK.NetworkRequest.NetworkRequest, platform: 'unix'|'win'):
Promise<string> {
let command: string[] = [];
// Most of these headers are derived from the URL and are automatically added by cURL.
// The |Accept-Encoding| header is ignored to prevent decompression errors. crbug.com/1015321
const ignoredHeaders =
new Set<string>(['accept-encoding', 'host', 'method', 'path', 'scheme', 'version', 'authority', 'protocol']);
function escapeStringWin(str: string): string {
/* Always escape the " characters so that we can use caret escaping.
Because cmd.exe parser and MS Crt arguments parsers use some of the
same escape characters, they can interact with each other in
horrible ways, the order of operations is critical.
Replace \ with \\ first because it is an escape character for certain
conditions in both parsers.
Replace all " with "" so that a quote in the value cannot end the
quoted argument in either shell. After caret escaping it becomes
^"^". cmd.exe strips the carets, and inside a quoted argument the
MS Crt parser reads "" as a literal " and stays in quoted mode.
PowerShell treats neither ^ nor \ as an escape: it sees the string
close and immediately reopen around a bare ^, so the value stays a
single argument and its text stays quoted. With \" PowerShell would
end the string at the quote and run whatever follows a ; or |.
Then escape all characters we are not sure about with ^ to ensure it
gets to MS Crt parser safely.
The % character is special because MS Crt parser will try and look for
ENV variables and fill them in its place. We cannot escape them with %
and cannot escape them with ^ (because it's cmd.exe's escape not MS Crt
parser); So we can get cmd.exe parser to escape the character after it,
if it is followed by a valid beginning character of an ENV variable.
This ensures we do not try and double escape another ^ if it was placed
by the previous replace.
Lastly we replace new lines with ^ and TWO new lines because the first
new line is there to enact the escape command the second is the character
to escape (in this case new line).
All other whitespace characters are replaced with a single space, as there
is no way to enter their literal values in a command line, and they do break
the command allowing for injection.
*/
const encapsChars = '^"';
return encapsChars +
str.replace(/\\/g, '\\\\')
.replace(/"/g, '""')
.replace(/[^a-zA-Z0-9\s_\-:=+~'\/.',?;*]/g, '^$&')
.replace(/%(?=[a-zA-Z0-9_])/g, '%^')
.replace(/[^ -~\r\n]/g, ' ')
.replace(/\r?\n|\r/g, '^\n\n') +
encapsChars;
}
function escapeStringPosix(str: string): string {
function escapeCharacter(x: string): string {
const code = x.charCodeAt(0);
let hexString = code.toString(16);
// Zero pad to four digits to comply with ANSI-C Quoting:
// http://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
while (hexString.length < 4) {
hexString = '0' + hexString;
}
return '\\u' + hexString;
}
if (/[\0-\x1F\x7F-\x9F!]|\'/.test(str)) {
// Use ANSI-C quoting syntax.
return '$\'' +
str.replace(/\\/g, '\\\\')
.replace(/\'/g, '\\\'')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/[\0-\x1F\x7F-\x9F!]/g, escapeCharacter) +
'\'';
}
// Use single quote syntax.
return '\'' + str + '\'';
}
// cURL command expected to run on the same platform that DevTools run
// (it may be different from the inspected page platform).
const escapeString = platform === 'win' ? escapeStringWin : escapeStringPosix;
const validUrl = NetworkLogView.#getValidClipboardUrl(request.url());
if (!validUrl) {
return i18nString(UIStrings.unsupportedUrlScheme, {PH1: '#'});
}
command.push('--url ' + escapeString(validUrl).replace(/[[{}\]]/g, '\\$&'));
let inferredMethod = 'GET';
const data = [];
const formData = await request.requestFormData();
if (formData) {
// Note that formData is not necessarily urlencoded because it might for example
// come from a fetch request made with an explicitly unencoded body.
data.push('--data-raw ' + escapeString(formData));
ignoredHeaders.add('content-length');
inferredMethod = 'POST';
}
if (request.requestMethod !== inferredMethod) {
command.push('-X ' + escapeString(request.requestMethod));
}
const requestHeaders = request.requestHeaders();
for (let i = 0; i < requestHeaders.length; i++) {
const header = requestHeaders[i];
const name = header.name.replace(/^:/, ''); // Translate SPDY v3 headers to HTTP headers.
if (ignoredHeaders.has(name.toLowerCase())) {
continue;
}
const value = header.value;
if (!value.trim()) {
// A header passed with -H with no value or only whitespace as its
// value tells curl to not set the header at all. To post an empty
// header, you have to terminate it with a semicolon.
command.push('-H ' + escapeString(name + ';'));
} else if (name.toLowerCase() === 'cookie' && value.includes('=')) {
// If value contains no '=', curl treats it as a filename to read
// cookies from, which would be a security risk. Fall back to -H in
// that case.
command.push('-b ' + escapeString(value));
} else {
command.push('-H ' + escapeString(name + ': ' + value));
}
}
command = command.concat(data);
if (request.securityState() === Protocol.Security.SecurityState.Insecure) {
command.push('--insecure');
}
return 'curl ' + command.join(command.length >= 3 ? (platform === 'win' ? ' ^\n ' : ' \\\n ') : ' ');
}
async #generateAllCurlCommand(requests: SDK.NetworkRequest.NetworkRequest[],
platform: 'unix'|'win'): Promise<string> {
const nonBlobRequests = this.#filterOutBlobRequests(requests);
const commands =
await Promise.all(nonBlobRequests.map(request => NetworkLogView.generateCurlCommand(request, platform)));
if (platform === 'win') {
return commands.join(' &\r\n');
}
return commands.join(' ;\n');
}
async #generatePowerShellCommand(request: SDK.NetworkRequest.NetworkRequest): Promise<string> {
const command = [];
const ignoredHeaders = new Set<string>([
'host',
'connection',
'proxy-connection',
'content-length',
'expect',
'range',
'content-type',
'user-agent',
'cookie',
]);
function escapeString(str: string): string {
return '"' +
str.replace(/[`\$"]/g, '`$&').replace(/[^\x20-\x7E]/g, char => '$([char]' + char.charCodeAt(0) + ')') + '"';
}
/**
* Generate a WebRequestSession object with the UserAgent and Cookie header values.
* This is used to pass the user-agent and cookie headers to Invoke-WebRequest because the Invoke-WebRequest
* command does not allow setting these headers through the -Headers parameter. See docs at:
* https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.1#parameters
**/
function generatePowerShellSession(request: SDK.NetworkRequest.NetworkRequest): string|null {
const requestHeaders = request.requestHeaders();
const props = [];
const userAgentHeader = requestHeaders.find(({name}) => name.toLowerCase() === 'user-agent');
if (userAgentHeader) {
props.push(`$session.UserAgent = ${escapeString(userAgentHeader.value)}`);
}
for (const includedCookie of request.includedRequestCookies()) {
const name = escapeString(includedCookie.cookie.name());
const value = escapeString(includedCookie.cookie.value());
const domain = escapeString(includedCookie.cookie.domain());
props.push(`$session.Cookies.Add((New-Object System.Net.Cookie(${name}, ${value}, "/", ${domain})))`);
}
if (props.length) {
return '$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession\n' + props.join('\n') + '\n';
}
return null;
}
const validUrl = NetworkLogView.#getValidClipboardUrl(request.url());
if (!validUrl) {
return i18nString(UIStrings.unsupportedUrlScheme, {PH1: '#'});
}
command.push('-Uri ' + escapeString(validUrl));
if (request.requestMethod !== 'GET') {
command.push('-Method ' + escapeString(request.requestMethod));
}
const session = generatePowerShellSession(request);
if (session) {
command.push('-WebSession $session');
}
const requestHeaders = request.requestHeaders();
const headerNameValuePairs = [];
for (const header of requestHeaders) {
const name = header.name.replace(/^:/, ''); // Translate h2 headers to HTTP headers.
if (ignoredHeaders.has(name.toLowerCase())) {
continue;
}
headerNameValuePairs.push(escapeString(name) + '=' + escapeString(header.value));
}
if (headerNameValuePairs.length) {
command.push('-Headers @{\n' + headerNameValuePairs.join('\n ') + '\n}');
}
const contentTypeHeader = requestHeaders.find(({name}) => name.toLowerCase() === 'content-type');
if (contentTypeHeader) {
command.push('-ContentType ' + escapeString(contentTypeHeader.value));
}
const formData = await request.requestFormData();
if (formData) {
const body = escapeString(formData);
if (/[^\x20-\x7E]/.test(formData)) {
command.push('-Body ([System.Text.Encoding]::UTF8.GetBytes(' + body + '))');
} else {
command.push('-Body ' + body);
}
}
// The -UseBasicParsing parameter prevents Invoke-WebRequest from using the IE engine for parsing. Basic
// parsing is the default behavior in PowerShell 6.0.0+ and the parameter is included here for backwards
// compatibility only.
const prelude = session || '';
return prelude + 'Invoke-WebRequest -UseBasicParsing ' + command.join(command.length >= 3 ? ' `\n' : ' ');
}
async #generateAllPowerShellCommand(requests: SDK.NetworkRequest.NetworkRequest[]): Promise<string> {
const nonBlobRequests = this.#filterOutBlobRequests(requests);
const commands = await Promise.all(nonBlobRequests.map(request => this.#generatePowerShellCommand(request)));
return commands.join(';\r\n');
}
static getDCLEventColor(): string {
return '--sys-color-blue';
}
static getLoadEventColor(): string {
return '--sys-color-error';
}
}
export function computeStackTraceText(stackTrace: Protocol.Runtime.StackTrace): string {
let stackTraceText = '';
for (const frame of stackTrace.callFrames) {
const functionName = UI.UIUtils.beautifyFunctionName(frame.functionName);
stackTraceText += `${functionName} @ ${frame.url}:${frame.lineNumber + 1}\n`;
}
if (stackTrace.parent) {
stackTraceText += computeStackTraceText(stackTrace.parent);
}
return stackTraceText;
}
const filteredNetworkRequests = new WeakSet<NetworkRequestNode>();
export function isRequestFilteredOut(request: NetworkRequestNode): boolean {
return filteredNetworkRequests.has(request);
}
export const HTTPSchemas = {
http: true,
https: true,
ws: true,
wss: true,
};
const searchKeys: string[] = Object.values(NetworkForward.UIFilter.FilterType);
export interface GroupLookupInterface {
groupNodeForRequest(request: SDK.NetworkRequest.NetworkRequest): NetworkGroupNode|null;
reset(): void;
}
export const overrideFilter = {
yes: 'yes',
no: 'no',
content: 'content',
headers: 'headers',
};
export type Filter = (request: SDK.NetworkRequest.NetworkRequest) => boolean;
export interface MoreFiltersViewInput {
activeFiltersCount: number;
tooltip: string;
hideDataURLs: boolean;
onHideDataURLsChange: () => void;
hideChromeExtensions: boolean;
onHideChromeExtensionsChange: () => void;
showBlockedCookiesOnly: boolean;
onShowBlockedCookiesOnlyChange: () => void;
onlyBlockedRequests: boolean;
onOnlyBlockedRequestsChange: () => void;
onlyThirdParty: boolean;
onOnlyThirdPartyChange: () => void;
}
export type MoreFiltersView = (input: MoreFiltersViewInput, output: undefined, target: HTMLElement) => void;
export const MORE_FILTERS_DEFAULT_VIEW: MoreFiltersView = (input, _output, target) => {
const openMenu = (event: Event): void => {
const buttonElement = event.currentTarget as HTMLElement;
const contextMenu = new UI.ContextMenu.ContextMenu(event, {
useSoftMenu: true,
keepOpen: true,
x: buttonElement.getBoundingClientRect().left,
y: buttonElement.getBoundingClientRect().top + buttonElement.offsetHeight,
onSoftMenuClosed: () => setTimeout(() => buttonElement.removeAttribute('aria-expanded'), 50),
});
contextMenu.defaultSection().appendCheckboxItem(i18nString(UIStrings.hideDataUrls), input.onHideDataURLsChange, {
checked: input.hideDataURLs,
tooltip: i18nString(UIStrings.hidesDataAndBlobUrls),
jslogContext: 'hide-data-urls',
});
contextMenu.defaultSection().appendCheckboxItem(i18nString(UIStrings.chromeExtensions),
input.onHideChromeExtensionsChange, {
checked: input.hideChromeExtensions,
tooltip: i18nString(UIStrings.hideChromeExtension),
jslogContext: 'hide-extension-urls',
});
contextMenu.defaultSection().appendSeparator();
contextMenu.defaultSection().appendCheckboxItem(i18nString(UIStrings.hasBlockedCookies),
input.onShowBlockedCookiesOnlyChange, {
checked: input.showBlockedCookiesOnly,
tooltip: i18nString(UIStrings.onlyShowRequestsWithBlockedCookies),
jslogContext: 'only-blocked-response-cookies',
});
contextMenu.defaultSection().appendCheckboxItem(i18nString(UIStrings.blockedRequests),
input.onOnlyBlockedRequestsChange, {
checked: input.onlyBlockedRequests,
tooltip: i18nString(UIStrings.onlyShowBlockedRequests),
jslogContext: 'only-blocked-requests',
});
contextMenu.defaultSection().appendCheckboxItem(i18nString(UIStrings.thirdParty), input.onOnlyThirdPartyChange, {
checked: input.onlyThirdParty,
tooltip: i18nString(UIStrings.onlyShowThirdPartyRequests),
jslogContext: 'only-3rd-party-requests',
});
buttonElement.setAttribute('aria-expanded', 'true');
void contextMenu.show();
};
// clang-format off
render(html`
<button
class="toolbar-button toolbar-item toolbar-has-dropdown dropdown-filterbar"
title=${input.tooltip}
aria-label=${input.tooltip}
aria-haspopup="true"
@click=${openMenu}>
<devtools-adorner
class="active-filters-count"
?hidden=${input.activeFiltersCount === 0}
.name=${'countWrapper'}>
<span>${input.activeFiltersCount}</span>
</devtools-adorner>
<div class="toolbar-text">${i18nString(UIStrings.moreFilters)}</div>
<devtools-icon
name="triangle-down"
class="toolbar-dropdown-arrow">
</devtools-icon>
</button>
`, target, {
container: {
attributes: {
'aria-label': 'Show only/hide requests dropdown',
jslog: VisualLogging.dropDown('more-filters').track({click: true}),
},
},
});
// clang-format on
};
export class MoreFiltersDropDownUI extends Common.ObjectWrapper.ObjectWrapper<UI.FilterBar.FilterUIEventTypes>
implements UI.FilterBar.FilterUI {
readonly #filterElement: HTMLDivElement;
readonly #view: MoreFiltersView;
#networkHideDataURLSetting: Common.Settings.Setting<boolean>;
#networkHideChromeExtensionsSetting: Common.Settings.Setting<boolean>;
#networkShowBlockedCookiesOnlySetting: Common.Settings.Setting<boolean>;
#networkOnlyBlockedRequestsSetting: Common.Settings.Setting<boolean>;
#networkOnlyThirdPartySetting: Common.Settings.Setting<boolean>;
constructor(view: MoreFiltersView = MORE_FILTERS_DEFAULT_VIEW) {
super();
this.#view = view;
this.#networkHideDataURLSetting = Common.Settings.Settings.instance().createSetting('network-hide-data-url', false);
this.#networkHideChromeExtensionsSetting =
Common.Settings.Settings.instance().createSetting('network-hide-chrome-extensions', false);
this.#networkShowBlockedCookiesOnlySetting =
Common.Settings.Settings.instance().createSetting('network-show-blocked-cookies-only-setting', false);
this.#networkOnlyBlockedRequestsSetting =
Common.Settings.Settings.instance().createSetting('network-only-blocked-requests', false);
this.#networkOnlyThirdPartySetting =
Common.Settings.Settings.instance().createSetting('network-only-third-party-setting', false);
this.#networkHideDataURLSetting.addChangeListener(this.#onSettingChanged, this);
this.#networkHideChromeExtensionsSetting.addChangeListener(this.#onSettingChanged, this);
this.#networkShowBlockedCookiesOnlySetting.addChangeListener(this.#onSettingChanged, this);
this.#networkOnlyBlockedRequestsSetting.addChangeListener(this.#onSettingChanged, this);
this.#networkOnlyThirdPartySetting.addChangeListener(this.#onSettingChanged, this);
this.#filterElement = document.createElement('div');
this.performUpdate();
}
#onSettingChanged(): void {
this.performUpdate();
this.dispatchEventToListeners(UI.FilterBar.FilterUIEvents.FILTER_CHANGED);
}
selectedFilters(): string[] {
const filters = [
...this.#networkHideDataURLSetting.get() ? [i18nString(UIStrings.hideDataUrls)] : [],
...this.#networkHideChromeExtensionsSetting.get() ? [i18nString(UIStrings.chromeExtensions)] : [],
...this.#networkShowBlockedCookiesOnlySetting.get() ? [i18nString(UIStrings.hasBlockedCookies)] : [],
...this.#networkOnlyBlockedRequestsSetting.get() ? [i18nString(UIStrings.blockedRequests)] : [],
...this.#networkOnlyThirdPartySetting.get() ? [i18nString(UIStrings.thirdParty)] : [],
];
return filters;
}
performUpdate(): void {
const selectedFilters = this.selectedFilters();
const tooltip = selectedFilters.length ? selectedFilters.join(', ') : i18nString(UIStrings.showOnlyHideRequests);
this.#view(
{
activeFiltersCount: selectedFilters.length,
tooltip,
hideDataURLs: this.#networkHideDataURLSetting.get(),
onHideDataURLsChange: () => {
this.#networkHideDataURLSetting.set(!this.#networkHideDataURLSetting.get());
},
hideChromeExtensions: this.#networkHideChromeExtensionsSetting.get(),
onHideChromeExtensionsChange: () => {
this.#networkHideChromeExtensionsSetting.set(!this.#networkHideChromeExtensionsSetting.get());
},
showBlockedCookiesOnly: this.#networkShowBlockedCookiesOnlySetting.get(),
onShowBlockedCookiesOnlyChange: () => {
this.#networkShowBlockedCookiesOnlySetting.set(!this.#networkShowBlockedCookiesOnlySetting.get());
},
onlyBlockedRequests: this.#networkOnlyBlockedRequestsSetting.get(),
onOnlyBlockedRequestsChange: () => {
this.#networkOnlyBlockedRequestsSetting.set(!this.#networkOnlyBlockedRequestsSetting.get());
},
onlyThirdParty: this.#networkOnlyThirdPartySetting.get(),
onOnlyThirdPartyChange: () => {
this.#networkOnlyThirdPartySetting.set(!this.#networkOnlyThirdPartySetting.get());
},
},
undefined,
this.#filterElement,
);
}
isActive(): boolean {
return this.selectedFilters().length !== 0;
}
element(): HTMLDivElement {
return this.#filterElement;
}
}