haba713
haba713

Reputation: 2687

Breaking JavaScript execution when cookie is set

Is it possible to break javascript execution in browser developer tools always when a cookie is set (without setting JS breakpoints explicitly)?

document.cookie = '...';

Upvotes: 28

Views: 16248

Answers (5)

haba713
haba713

Reputation: 2687

Adding this snippet in the beginning of the html → head block works fine:

<script type="text/javascript">
    function debugAccess(obj, prop, debugGet){
        var origValue = obj[prop];
        Object.defineProperty(obj, prop, {
            get: function () {
                if ( debugGet )
                    debugger;
                return origValue;
            },
            set: function(val) {
                debugger;
                return origValue = val;
            }
        });
    };
    debugAccess(document, 'cookie');
</script>

See this Angular University page for more information.

Upvotes: 36

fflorent
fflorent

Reputation: 1656

This should work (run it in a console):

origDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Object.defineProperty(document, 'cookie', {
  get() {
    return origDescriptor.get.call(this);
  },
  set(value) {
    debugger;
    return origDescriptor.set.call(this, value);
  },
  enumerable: true,
  configurable: true
});

Upvotes: 15

erroric
erroric

Reputation: 1011

A better way than overriding the whole HTMLDocument.prototype cookie property is to use Reflect and Proxy. This way, instead of having to provide an override for every method of the cookie property, you only have to provide the particular method (ie. when the cookie is set).

Reflect.setPrototypeOf(document, new Proxy(Reflect.getPrototypeOf(document), {
  set(target, key, value, thisArg) {
    if (key === 'cookie') {
      // when document.cookie is assigned a value, we end up here.
      debugger;
    }

    // flow through to the original object assignment
    return Reflect.set(...arguments)
  }
}));

Upvotes: 1

dancl
dancl

Reputation: 727

In Chrome dev-tools, you can right click on a cookie in the application cookies and select 'show request with this cookie'

so it's not an interception, but if your goal is to identify where a cookie comes from then it's a good way.

Upvotes: -3

D. Piep
D. Piep

Reputation: 13

Try setting it in a If statement.

if(document.cookie.indexOf('...') >= 0){
  debugger;
}

note: when using firefox your console has to be open. in chrome this is not the case.

Upvotes: -5

Related Questions