diff --git a/goldens/public-api/common/errors.api.md b/goldens/public-api/common/errors.api.md index f93c0f8544f..58827760e4e 100644 --- a/goldens/public-api/common/errors.api.md +++ b/goldens/public-api/common/errors.api.md @@ -53,6 +53,8 @@ export const enum RuntimeErrorCode { // (undocumented) REQUIRED_INPUT_MISSING = 2954, // (undocumented) + SCROLL_RESTORATION_UNSUPPORTED = 2400, + // (undocumented) SUSPICIOUS_DATE_FORMAT = 2300, // (undocumented) TOO_MANY_PRELOADED_IMAGES = 2961, diff --git a/packages/common/src/errors.ts b/packages/common/src/errors.ts index 72e02440d39..575bfc7c5c9 100644 --- a/packages/common/src/errors.ts +++ b/packages/common/src/errors.ts @@ -38,6 +38,9 @@ export const enum RuntimeErrorCode { NO_PLURAL_MESSAGE_FOUND = 2308, VALUE_NOT_A_NUMBER = 2309, + // Miscellaneous errors + SCROLL_RESTORATION_UNSUPPORTED = 2400, + // Keep 2800 - 2900 for Http Errors. // Image directive errors diff --git a/packages/common/src/viewport_scroller.ts b/packages/common/src/viewport_scroller.ts index e6a36d5e52f..d25e10d4f1e 100644 --- a/packages/common/src/viewport_scroller.ts +++ b/packages/common/src/viewport_scroller.ts @@ -6,7 +6,13 @@ * found in the LICENSE file at https://angular.dev/license */ -import {inject, ɵɵdefineInjectable, DOCUMENT} from '@angular/core'; +import { + inject, + ɵɵdefineInjectable, + DOCUMENT, + ɵformatRuntimeError as formatRuntimeError, +} from '@angular/core'; +import {RuntimeErrorCode} from './errors'; /** * Defines a scroll position manager. Implemented by `BrowserViewportScroller`. @@ -131,7 +137,22 @@ export class BrowserViewportScroller implements ViewportScroller { * Disables automatic scroll restoration provided by the browser. */ setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void { - this.window.history.scrollRestoration = scrollRestoration; + try { + this.window.history.scrollRestoration = scrollRestoration; + } catch { + console.warn( + formatRuntimeError( + RuntimeErrorCode.SCROLL_RESTORATION_UNSUPPORTED, + ngDevMode && + 'Failed to set `window.history.scrollRestoration`. ' + + 'This may occur when:\n' + + '• The script is running inside a sandboxed iframe\n' + + '• The window is partially navigated or inactive\n' + + '• The script is executed in an untrusted or special context (e.g., test runners, browser extensions, or content previews)\n' + + 'Scroll position may not be preserved across navigation.', + ), + ); + } } /**