diff --git a/src/index.js b/src/index.js index 2406e2f..483224a 100644 --- a/src/index.js +++ b/src/index.js @@ -26,7 +26,11 @@ export default class ScrollBehavior { /* istanbul ignore else: Travis browsers all support this */ if ('scrollRestoration' in window.history) { this._oldScrollRestoration = window.history.scrollRestoration; - window.history.scrollRestoration = 'manual'; + try { + window.history.scrollRestoration = 'manual'; + } catch (e) { + this._oldScrollRestoration = null; + } } else { this._oldScrollRestoration = null; } @@ -117,7 +121,11 @@ export default class ScrollBehavior { stop() { /* istanbul ignore if: not supported by any browsers on Travis */ if (this._oldScrollRestoration) { - window.history.scrollRestoration = this._oldScrollRestoration; + try { + window.history.scrollRestoration = this._oldScrollRestoration; + } catch (e) { + /* silence */ + } } off(window, 'scroll', this._onWindowScroll); diff --git a/test/ScrollBehavior.test.js b/test/ScrollBehavior.test.js index 0bce861..ae16d0b 100644 --- a/test/ScrollBehavior.test.js +++ b/test/ScrollBehavior.test.js @@ -65,6 +65,29 @@ describe('ScrollBehavior', () => { }, ]); }); + + it('should not crash when history is not available', (done) => { + Object.defineProperty(window.history, 'scrollRestoration', { + value: 'auto', + // See https://github.com/taion/scroll-behavior/issues/126 + writable: false, + enumerable: true, + configurable: true, + }); + + const history = withRoutes(withScroll(createHistory())); + + unlisten = run(history, [ + () => { + expect(scrollTop(window)).to.equal(0); + + delete window.history.scrollRestoration; + window.history.scrollRestoration = 'auto'; + + done(); + }, + ]); + }); }); describe('custom behavior', () => {