@@ -324,14 +324,37 @@ function getLcpResponseObject(lcpUrl) {
324324 return responseObject ;
325325}
326326
327+ function getParameterCaseInsensitive ( object , key ) {
328+ return object [ Object . keys ( object ) . find ( k => k . toLowerCase ( ) === key . toLowerCase ( ) ) ] ;
329+ }
330+
327331function getSpeculationRules ( ) {
328- return Array . from ( document . querySelectorAll ( 'script[type=speculationrules]' ) ) . map ( script => {
329- try {
330- return JSON . parse ( script . innerHTML ) ;
331- } catch ( error ) {
332- return null ;
333- }
334- } ) ;
332+ // Get rules from the HTML
333+ const htmlRules = Array . from ( document . querySelectorAll ( 'script[type=speculationrules]' ) ) . map ( script => {
334+ try {
335+ return JSON . parse ( script . innerHTML ) ;
336+ } catch ( error ) {
337+ return null ;
338+ }
339+ } ) ;
340+
341+ // Get rules from Speculation-Rules HTTP responses
342+ // There is an assumption this is actually used on the page but by checking both the `content-type`
343+ // and the `sec-fetch-dest`, that should be the case.
344+ const httpRules = Array . from (
345+ response_bodies
346+ . filter ( req => getParameterCaseInsensitive ( req . response_headers , 'content-type' ) === 'application/speculationrules+json' )
347+ . filter ( req => getParameterCaseInsensitive ( req . request_headers , 'sec-fetch-dest' ) === 'speculationrules' )
348+ . map ( req => {
349+ try {
350+ return { url : req . url , rule : JSON . parse ( req . response_body ) } ;
351+ } catch ( error ) {
352+ return { url : req . url , errorName : error . name , errorMessage : error . message } ;
353+ }
354+ } )
355+ ) ;
356+
357+ return { htmlRules : htmlRules , httpHeaderRules : httpRules } ;
335358}
336359
337360return Promise . all ( [ getLcpElement ( ) ] ) . then ( ( [ lcp_elem_stats ] ) => {
@@ -369,5 +392,5 @@ return Promise.all([getLcpElement()]).then(([lcp_elem_stats]) => {
369392 speculation_rules : getSpeculationRules ( ) ,
370393 } ;
371394} ) . catch ( error => {
372- return { error} ;
395+ return { errorName : error . name , errorMessage : error . message } ;
373396} ) ;
0 commit comments