Skip to content

Instantly share code, notes, and snippets.

@david-risney
Created June 15, 2016 17:45
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save david-risney/af6f7912ea171b9076d3ba3ebd54a355 to your computer and use it in GitHub Desktop.
JavaScript data breakpoint
function ValueBreakpoint(parent, fullNamePath) {
var name = fullNamePath[0];
var childNamePath = fullNamePath.slice(1);
var innerValue = parent[name];
var childBreakpoints = [];
function applyChildValueBreakpoints() {
if (childNamePath.length > 0 && innerValue) {
childBreakpoints.push(new ValueBreakpoint(innerValue, childNamePath));
}
}
applyChildValueBreakpoints();
Object.defineProperty(parent, name, {
get: (function () {
if (!childNamePath.length) { debugger; }
return innerValue;
}).bind(this),
set: (function (newValue) {
if (!childNamePath.length) { debugger; }
innerValue = newValue;
applyChildValueBreakpoints();
}).bind(this),
enumerable: true,
configurable: true
});
};
// Breaks when setting or getting a property on window.object1.object2.object3
new ValueBreakpoint(window, ["object1", "object2", "object3"]);
@david-risney
Copy link
Author

Data breakpoints in JavaScript

The other day I had to debug a JavaScript UWA that was failing when trying to use an undefined property. In a previous OS build this code would run and the property was defined. I wanted something similar to windbg/cdb's ba command that lets me set a breakpoint on read or writes to a memory location so I could see what was creating the object in the previous OS build and what that code was doing now in the current OS build. I couldn't find such a breakpoint mechanism in Visual Studio or F12 so I wrote a little script to approximate JavaScript data breakpoints.

The script creates a stub object with a getter and setter. It actually performs the get or set but also calls debugger; to break in the debugger. In order to handle my case of needing to break when window.object1.object2 was created or accessed, I further had it recursively set up such stub objects for the matching property names.

Its not perfect because it is an enumerable property and shows up in hasOwnProperty and likely other places. But for your average code that checks for the existence of a property via if (object.property) it works well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment