Skip to content

Instantly share code, notes, and snippets.

@luin
Last active August 2, 2023 10:58
Show Gist options
  • Save luin/40957106f8c089cf74819f41e6eebbce to your computer and use it in GitHub Desktop.
Save luin/40957106f8c089cf74819f41e6eebbce to your computer and use it in GitHub Desktop.
Scripts for debugging unexpected scrolling
function debugScrolling() {
/* eslint-disable func-names, no-debugger, no-console, prefer-rest-params */
const fnOnScroll = function(reason) {
console.log(reason);
debugger;
};
// scrollIntoView, scrollIntoViewIfNeeded, scrollTo
const scrollMethods = [
'scrollIntoView',
'scrollIntoViewIfNeeded',
'scrollTo',
];
scrollMethods.forEach(method => {
const origin = HTMLElement.prototype[method];
HTMLElement.prototype[method] = function() {
fnOnScroll(method);
origin.apply(this, arguments);
};
});
const originalFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function(options) {
if (!options || !options.preventScroll) {
fnOnScroll('focus');
}
originalFocus.apply(this, arguments);
};
const originalScrollTop = getPropertyDescriptor(
HTMLElement.prototype,
'scrollTop',
);
Object.defineProperty(HTMLElement.prototype, 'scrollTop', {
get() {
return originalScrollTop.get.apply(this, arguments);
},
set() {
fnOnScroll('scrollTop');
return originalScrollTop.set.apply(this, arguments);
},
});
const originalScrollTo = window.scrollTo;
window.scrollTo = function() {
fnOnScroll('window.scrollTop');
return originalScrollTo.apply(this, arguments);
};
const originalScrollBy = window.scrollBy;
window.scrollBy = function() {
fnOnScroll('window.scrollBy');
return originalScrollBy.apply(this, arguments);
};
function getPropertyDescriptor(object, propertyName) {
const descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
if (!object) {
throw new Error('descriptor not found');
}
if (!descriptor) {
return getPropertyDescriptor(Object.getPrototypeOf(object), propertyName);
}
return descriptor;
}
}
debugScrolling();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment