Skip to content

Instantly share code, notes, and snippets.

@fed
Created September 3, 2019 09:00
Show Gist options
  • Save fed/d906d7fa88cda522604d372e40f5c5f7 to your computer and use it in GitHub Desktop.
Save fed/d906d7fa88cda522604d372e40f5c5f7 to your computer and use it in GitHub Desktop.
Focus Debugging Snippet

Debugging Snippet

This snippet is useful for debugging things like who's setting focus on a particular element.

DevTools > Source tab > Top left panel > Select snippet > New snippet

Disclaimer: this snippet only breaks when <HTMLElement>.focus() is called -- if you want to break on focus events, Safari's debugger lets you set DOM event breakpoints.

Also, it's often helpful to use focusin/focusout events for debugging since they bubble.

(function () {
window.__helper = window.__helper || {};
window.__helper.detect = function (obj, name) {
var localVar;
obj = obj || window;
Object.defineProperty(obj, name, {
get: function () {
return localVar;
},
set: function (value) {
debugger;
localVar = value;
}
})
};
window.__helper.nativeEventDebugger = window.__helper.nativeEventDebugger || {
scrollTop: function (fnOnScroll) {
var originalScrollTop = getPropertyDescriptor(HTMLElement.prototype, "scrollTop");
Object.defineProperty(HTMLElement.prototype, "scrollTop", {
get: function(){
return originalScrollTop.get.apply(this, arguments);
},
set: function(){
fnOnScroll();
return originalScrollTop.set.apply(this, arguments);
}
});
var originalScrollTo = window.scrollTo;
window.scrollTo = function(){
fnOnScroll(...arguments);
return originalScrollTo.apply(this, arguments);
}
var originalScrollBy = window.scrollBy;
window.scrollBy = function(){
fnOnScroll(...arguments);
return originalScrollBy.apply(this, arguments);
}
function getPropertyDescriptor(object, propertyName){
var descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
if (!object){
throw new Error("descriptor not found");
}
if (!descriptor) {
return getPropertyDescriptor(Object.getPrototypeOf(object), propertyName);
}
return descriptor;
}
},
focus: function (fn) {
var originalFocus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function () {
console.log('focus: ', this);
fn.apply(this, arguments);
return originalFocus.apply(this, arguments);
}
},
alert: function (fn) {
var originalAlert = window.alert.bind(window);
window.alert = function () {
fn();
originalAlert(arguments);
}
}
};
// ==========================================
// Select the method in here
// ==========================================
// Start using the snippet here
// window.__helper.nativeEventDebugger['focus'](function () {
// debugger;
// });
// change the method name in here like 'focus' or 'scrollTop' or anything else you want to observe
// To have breakpoint pause when variabble value changes
// window.__helper.detect(whatEverObject, 'variableKeyIWantToObserve');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment