Skip to content

Instantly share code, notes, and snippets.

@smstuebe
Created November 9, 2017 13:35
Show Gist options
  • Save smstuebe/ae8b81ffe54634ea4aac3c4090131402 to your computer and use it in GitHub Desktop.
Save smstuebe/ae8b81ffe54634ea4aac3c4090131402 to your computer and use it in GitHub Desktop.
Some javascript debug helpers for Tampermonkey
// ==UserScript==
// @name Sven's awesome debug collection
// @namespace http://tampermonkey.net/
// @version 0.1
// @description debug the stuff
// @include *
// @grant none
// ==/UserScript==
(function() {
'use strict';
console.log("Press F8 when the console is open to trigger 'debugger'");
console.log("use breakOn(obj, 'propertyName') to break on changes of the property of obj.");
console.log("other example: breakOn(obj, 'propertyName', null, (val) => { console.log(val); return val > 400; }) to break on changes of the property of obj if new value > 400.");
function KeyCheck(e) {
// Key code 24 is 'F8'
if(e.keyCode === 24) {
debugger;
}
}
window.addEventListener('keydown', KeyCheck, false);
window.breakOn = function(obj, propertyName, mode, func) {
// this is directly from https://github.com/paulmillr/es6-shim
function getPropertyDescriptor(obj, name) {
var property = Object.getOwnPropertyDescriptor(obj, name);
var proto = Object.getPrototypeOf(obj);
while (property === undefined && proto !== null) {
property = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return property;
}
function verifyNotWritable() {
if (mode !== 'read')
throw "This property is not writable, so only possible mode is 'read'.";
}
var enabled = true;
var originalProperty = getPropertyDescriptor(obj, propertyName);
var newProperty = { enumerable: originalProperty.enumerable };
// write
if (originalProperty.set) {// accessor property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.set.call(this, val);
}
} else if (originalProperty.writable) {// value property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.value = val;
}
} else {
verifyNotWritable();
}
// read
newProperty.get = function(val) {
if(enabled && mode === 'read' && (!func || func && func(val)))
debugger;
return originalProperty.get ? originalProperty.get.call(this, val) : originalProperty.value;
}
Object.defineProperty(obj, propertyName, newProperty);
return {
disable: function() {
enabled = false;
},
enable: function() {
enabled = true;
}
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment