如何通过JavaScript Web API获取资源请求的请求类型(GET/POST)?
Great question! You're absolutely right that window.performance.getEntriesByType('resource') doesn't include HTTP request methods (GET, POST, etc.) by default—it's a common gotcha with the Resource Timing API. Let's break down two solid approaches to get this info depending on your browser support needs.
Solution 1: Use requestMethod (Modern Browsers)
Most modern browsers (Chrome 60+, Firefox 57+, Edge 79+, Safari 15.4+) extend the PerformanceResourceTiming interface with a requestMethod property, which directly exposes the HTTP method used for the resource request. This is the cleanest solution if you don't need to support older browsers.
Example Code
// Get existing resource entries with their methods const existingResources = window.performance.getEntriesByType('resource'); existingResources.forEach(entry => { if ('requestMethod' in entry) { console.log(`URL: ${entry.name} | Method: ${entry.requestMethod}`); } else { console.log(`URL: ${entry.name} | Method: (Not supported in this browser)`); } }); // Listen for future resource requests in real-time const resourceObserver = new PerformanceObserver((entryList) => { entryList.getEntries().forEach(entry => { if ('requestMethod' in entry) { console.log(`New resource loaded: ${entry.name} | Method: ${entry.requestMethod}`); } }); }); resourceObserver.observe({ entryTypes: ['resource'] });
Solution 2: Intercept XHR/Fetch Requests (Legacy Browser Support)
If you need to support older browsers that don't have requestMethod, you can wrap the native XMLHttpRequest and fetch APIs to track HTTP methods, then match those details against performance entries using URL and timing data.
Example Implementation
// Store request metadata: key = resource URL, value = { method, startTime } const requestMetadata = new Map(); // Wrap XMLHttpRequest to capture method and timing const originalXHR = XMLHttpRequest; XMLHttpRequest = function() { const xhr = new originalXHR(); const originalOpen = xhr.open; xhr.open = function(method, url) { requestMetadata.set(url, { method: method, startTime: performance.now() }); originalOpen.apply(this, arguments); }; return xhr; }; // Wrap fetch to capture method and timing const originalFetch = window.fetch; window.fetch = function(url, options = {}) { const method = options.method?.toUpperCase() || 'GET'; requestMetadata.set(url.toString(), { method: method, startTime: performance.now() }); return originalFetch.apply(this, arguments); }; // Helper to match performance entries with request methods function getResourcesWithMethods() { return window.performance.getEntriesByType('resource').map(entry => { const metadata = requestMetadata.get(entry.name); return { url: entry.name, method: metadata ? metadata.method : 'Unknown', startTime: entry.startTime, duration: entry.duration }; }); } // Example usage: Wait for resources to load, then log results setTimeout(() => { const resources = getResourcesWithMethods(); console.table(resources); }, 2000);
Important Notes
- Cached Resources: Resources loaded from cache might not trigger
fetch/XHRcalls, so their method might show as "Unknown". You can handle this by checking thetransferSizeproperty on performance entries (a value of 0 often indicates a cached resource). - URL Variations: If your app uses dynamic URL parameters or query strings, you may need to adjust the matching logic (e.g., strip query parameters before matching URLs).
- CORS Restrictions: For cross-origin resources, some performance entry properties may be redacted unless the server sets the
Timing-Allow-Originheader.
内容的提问来源于stack exchange,提问作者samk

