Skip to content

Commit ecf0fbd

Browse files
committed
Handle missing Web Crypto API in non-HTTPS contexts
Signed-off-by: Shyamsundar Gadde <[email protected]>
1 parent 1a7f906 commit ecf0fbd

File tree

1 file changed

+36
-19
lines changed

1 file changed

+36
-19
lines changed

plugins/optimization-detective/detect.js

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,17 @@ async function getAlreadySubmittedSessionStorageKey(
161161
currentUrl,
162162
urlMetricGroupStatus
163163
) {
164+
// Check if crypto.subtle is available.
165+
if ( ! window.crypto || ! window.crypto.subtle ) {
166+
// eslint-disable-next-line no-console
167+
console.warn(
168+
'[Optimization Detective] Web Crypto API is not available. This API is only available in secure contexts (HTTPS). Detection cannot proceed. If you are testing locally, ensure you use HTTPS or run on localhost.'
169+
);
170+
throw new Error(
171+
'Web Crypto API is unavailable in this context. Try using HTTPS or localhost.'
172+
);
173+
}
174+
164175
const message = [
165176
currentETag,
166177
currentUrl,
@@ -391,27 +402,33 @@ export default async function detect( {
391402
return;
392403
}
393404

394-
// Abort if the client already submitted a URL Metric for this URL and viewport group.
395-
const alreadySubmittedSessionStorageKey =
396-
await getAlreadySubmittedSessionStorageKey(
397-
currentETag,
398-
currentUrl,
399-
urlMetricGroupStatus
400-
);
401-
if ( alreadySubmittedSessionStorageKey in sessionStorage ) {
402-
const previousVisitTime = parseInt(
403-
sessionStorage.getItem( alreadySubmittedSessionStorageKey ),
404-
10
405-
);
406-
if (
407-
! isNaN( previousVisitTime ) &&
408-
( getCurrentTime() - previousVisitTime ) / 1000 < freshnessTTL
409-
) {
410-
log(
411-
'The current client session already submitted a fresh URL Metric for this URL so a new one will not be collected now.'
405+
let alreadySubmittedSessionStorageKey;
406+
try {
407+
// Abort if the client already submitted a URL Metric for this URL and viewport group.
408+
alreadySubmittedSessionStorageKey =
409+
await getAlreadySubmittedSessionStorageKey(
410+
currentETag,
411+
currentUrl,
412+
urlMetricGroupStatus
413+
);
414+
if ( alreadySubmittedSessionStorageKey in sessionStorage ) {
415+
const previousVisitTime = parseInt(
416+
sessionStorage.getItem( alreadySubmittedSessionStorageKey ),
417+
10
412418
);
413-
return;
419+
if (
420+
! isNaN( previousVisitTime ) &&
421+
( getCurrentTime() - previousVisitTime ) / 1000 < freshnessTTL
422+
) {
423+
log(
424+
'The current client session already submitted a fresh URL Metric for this URL so a new one will not be collected now.'
425+
);
426+
return;
427+
}
414428
}
429+
} catch ( err ) {
430+
warn( 'Unable to create session storage key: ' + err.message );
431+
return;
415432
}
416433

417434
// Abort if the viewport aspect ratio is not in a common range.

0 commit comments

Comments
 (0)