Breakpoint on property change

JavascriptDebuggingFirefoxGoogle ChromeFirebug

Javascript Problem Overview


Firebug for Firefox has a nice feature, called "Break on property change", where I can mark any property of any object, and it will stop JavaScript execution right before the change.

I'm trying to achieve the same in Google Chrome, and I can't find the function in Chrome debugger. How do I do this in Google Chrome?

Javascript Solutions


Solution 1 - Javascript

If you don't mind messing around with the source, you could redefine the property with an accessor.

// original object
var obj = {
    someProp: 10
};

// save in another property
obj._someProp = obj.someProp;

// overwrite with accessor
Object.defineProperty(obj, 'someProp', {
    get: function () {
        return obj._someProp;
    },

    set: function (value) {
        debugger; // sets breakpoint
        obj._someProp = value;
    }
});

Solution 2 - Javascript

Edit 2016.03: Object.observe is deprecated and removed in Chrome 50

Edit 2014.05: Object.observe was added in Chrome 36

Chrome 36 ships with native Object.observe implementation that can be leveraged here:

myObj = {a: 1, b: 2};
Object.observe(myObj, function (changes){
    console.log("Changes:");
    console.log(changes);
    debugger;
})
myObj.a = 42;

If you want it only temporarily, you should store callback in a variable and call Object.unobserve when done:

myObj = {a: 1, b: 2};
func = function() {debugger;}
Object.observe(myObj, func);
myObj.a = 42;
Object.unobserve(myObj, func);
myObj.a = 84;

Note that when using Object.observe, you'll not be notified when the assignment didn't change anything, e.g. if you've written myObj.a = 1.

To see the call stack, you need to enable "async call stack" option in Dev Tools:

chrome async call stack


Original answer (2012.07):

A console.watch sketch as suggested by @katspaugh:

var console = console || {}; // just in case
console.watch = function(oObj, sProp) {
   var sPrivateProp = "$_"+sProp+"_$"; // to minimize the name clash risk
   oObj[sPrivateProp] = oObj[sProp];

   // overwrite with accessor
   Object.defineProperty(oObj, sProp, {
       get: function () {
           return oObj[sPrivateProp];
       },

       set: function (value) {
           //console.log("setting " + sProp + " to " + value); 
           debugger; // sets breakpoint
           oObj[sPrivateProp] = value;
       }
   });
}

Invocation:

console.watch(obj, "someProp");

Compatibility:

  • In Chrome 20, you can paste it directly in Dev Tools at runtime!
  • For completeness: in Firebug 1.10 (Firefox 14), you have to inject it in your website (e.g. via Fiddler if you can't edit the source manually); sadly, functions defined from Firebug don't seem to break on debugger (or is it a matter of configuration? please correct me then), but console.log works.

Note that in Firefox, console.watch already exists, due to Firefox's non-standard Object.watch. Hence in Firefox, you can watch for changes natively:

>>> var obj = { foo: 42 }
>>> obj.watch('foo', function() { console.log('changed') })
>>> obj.foo = 69
changed
69

Edit: Object.watch was removed in Firefox 57.

Solution 3 - Javascript

There is a library for this: BreakOn()

If you add it to Chrome dev tools as a snippet (sources --> snippets --> right-click --> new --> paste this --> run), you can use it anytime.

enter image description here


To use it, open the dev-tools and run the snippet. Then to break when myObject.myProperty is changed, call this from the dev-console:

breakOn(myObject, 'myProperty');

You could also add the library to your project's debug-build so you don't need to call breakOn again every time you refresh the page.

Solution 4 - Javascript

This can also be done by using the new Proxy object whose purpose is exactly that: intercepting the reads and writes to the object that is wrapped by the Proxy. You simply wrap the object you would like to observe into a Proxy and use the new wrapped object instead of your original one.

Example:

const originalObject = {property: 'XXX', propertyToWatch: 'YYY'};
const watchedProp = 'propertyToWatch';
const handler = {
  set(target, key, value) {
    if (key === watchedProp) {
      debugger;
    }
    target[key] = value;
  }
};
const wrappedObject = new Proxy(originalObject, handler);

Now use wrappedObject where you would supply originalObject instead and examine the call stack on break.

Solution 5 - Javascript

function debugProperty(obj, propertyName) {
  // save in another property
  obj['_' + propertyName] = obj[propertyName];

  // overwrite with accessor
  Object.defineProperty(obj, propertyName, {
    get: function() {
      return obj['_' + propertyName];
    },

    set: function(value) {
      debugger; // sets breakpoint
      obj['_' + propertyName] = value;
    }
  });
}

Solution 6 - Javascript

Decided to write my own version of this solution, save it in a snippet in Chrome's DevTools, and wrapped it in an IIFE that should support both Node and Browsers. Also changed the observer to use a scope variable rather than a property on the object, such that there is no possibility of name clashes, and any code that enumerates keys will not "see" the new "private key" that is created:

(function (global) {
  global.observeObject = (obj, prop) => {
    let value

    Object.defineProperty(obj, prop, {
      get: function () {
        return value
      },

      set: function (newValue) {
        debugger
        value = newValue
      },
    })
  }
})(typeof process !== 'undefined' ? process : window)

Solution 7 - Javascript

Building on the excellent solution by Alexandos Katechis, here is a version of the snippet that does not disturb the original value of the property. I renamed it to better match what I'm thinking when I use it.

Usage:

  1. Add the snippet via Sources -> Snippets
  2. When needed, press Command-O and choose to run the breakOnChange snippet
  3. Call breakOnChange(anyObject, 'propertyName') in the console
  4. Take the action that causes the change
  5. Stops in debugger

This is very helpful for spotting things like a global library such as jQuery being stomped on by a third-party script.

(function (global) {
  global.breakOnChange = (obj, prop) => {
    let value = obj[prop]

    Object.defineProperty(obj, prop, {
      get: function () {
        return value
      },

      set: function (newValue) {
        debugger
        value = newValue
      },
    })
  }
})(typeof process !== 'undefined' ? process : window)

Solution 8 - Javascript

Chrome has this feature built-in in latest versions https://developers.google.com/web/updates/2015/05/view-and-change-your-dom-breakpoints.

So no more needs for custom libraries and solutions, just right click on DOM element in the inspector and choose 'Break on' -> 'attribute modifications' and that's it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArsen ZahrayView Question on Stackoverflow
Solution 1 - JavascriptkatspaughView Answer on Stackoverflow
Solution 2 - Javascriptjakub.gView Answer on Stackoverflow
Solution 3 - JavascriptBlueRaja - Danny PflughoeftView Answer on Stackoverflow
Solution 4 - JavascriptDima SlivinView Answer on Stackoverflow
Solution 5 - JavascriptRoland SoósView Answer on Stackoverflow
Solution 6 - JavascriptAlexandros KatechisView Answer on Stackoverflow
Solution 7 - JavascriptTom BoutellView Answer on Stackoverflow
Solution 8 - JavascriptIvica PuljicView Answer on Stackoverflow