Skip to content

Instantly share code, notes, and snippets.

@elvispt
Last active September 22, 2016 09:03
Show Gist options
  • Save elvispt/3d45a1d8057e06c89779d176cc1e15a9 to your computer and use it in GitHub Desktop.
Save elvispt/3d45a1d8057e06c89779d176cc1e15a9 to your computer and use it in GitHub Desktop.
dev browser snippets.
(function (_window) {
/**
* useful dev snippets
* Some of these where created by me, others obtained from: http://bgrins.github.io/devtools-snippets/
*/
var _that = {
// will get the list of events associated with the element. uses jQuery
elementEvents: function (elem) {
var el = elem;
if (!jQuery) {
console.warn('This snippet requires jQuery');
return;
}
if (!elem && $0) {
el = $0;
} else if (elem instanceof jQuery) {
el = elem[0];
} else if (typeof elem === 'string') {
el = $(elem)[0];
}
return $._data(el, "events");
},
// get performance data from requests
requestPerformanceData: function (grep) {
if (grep) {
return performance.getEntries().filter(function (entry) {
return entry.name.includes(grep);
});
}
return performance.getEntries();
},
// cssreload.js
// https://github.com/bgrins/devtools-snippets
// Removes then reloads all the CSS files in the current page
cssReload: function () {
function insertAfter(newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
function reloadStyleSheet(stylesheet) {
var element = stylesheet.ownerNode;
var clone = element.cloneNode(false);
clone.href = addRandomToUrl(clone.href);
clone.addEventListener("load", function() {
if (element.parentNode) {
element.parentNode.removeChild(element);
}
});
insertAfter(clone, element);
}
function addRandomToUrl(input) {
// prevent CSS caching
var hasRnd = /([?&])_=[^&]*/,
hasQueryString = /\?/,
hasHash = /(.+)#(.+)/,
hash = null,
rnd = Math.random();
var hashMatches = input.match(hasHash);
if (hashMatches) {
input = hashMatches[1];
hash = hashMatches[2];
}
url = hasRnd.test(input) ?
input.replace(hasRnd, "$1_=" + rnd) :
input + (hasQueryString.test(input) ? "&" : "?") + "_=" + rnd;
if (hash) url += '#' + hash;
return url;
}
[].forEach.call(document.styleSheets, function(styleSheet) {
if (!styleSheet.href) return;
console.log('reload ' + styleSheet.href);
reloadStyleSheet(styleSheet);
});
},
// download object as json file
saveObjectToFile: function (data, filename) {
if (!data) {
console.error('Console.save: No data');
return;
}
if (!filename) {
filename = 'console.json';
}
if (typeof data === "object") {
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'});
var e = document.createEvent('MouseEvents');
var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
},
// Print out data URLs for all images / canvases on the page.
dataurls: function () {
console.group("Data URLs");
[].forEach.call(document.querySelectorAll("img"), function(i) {
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
c.width = i.width;
c.height = i.height;
try {
ctx.drawImage(i, 0, 0);
console.log(i, c.toDataURL());
}
catch(e) {
console.log(i, "No Permission - try opening this image in a new tab and running the snippet again?", i.src);
}
});
[].forEach.call(document.querySelectorAll("canvas"), function(c) {
try {
console.log(c, c.toDataURL());
}
catch(e) {
console.log(c, "No Permission");
}
});
console.groupEnd("Data URLs");
},
// shows page form elements in a pretty table
formControls: function () {
var forms = document.querySelectorAll("form");
for (var i = 0, len = forms.length; i < len; i++) {
var tab = [ ];
console.group("HTMLForm quot;" + forms[i].name + "quot;: " + forms[i].action);
console.log("Element:", forms[i], "\nName: "+forms[i].name+"\nMethod: "+forms[i].method.toUpperCase()+"\nAction: "+forms[i].action || "null");
["input", "textarea", "select"].forEach(function (control) {
[].forEach.call(forms[i].querySelectorAll(control), function (node) {
tab.push({
"Element": node,
"Type": node.type,
"Name": node.name,
"Value": node.value,
"Pretty Value": (isNaN(node.value) || node.value === "" ? node.value : parseFloat(node.value))
});
});
});
console.table(tab);
console.groupEnd();
}
},
// outputs injected globals
detectGlobals: function () {
'use strict';
function getIframe() {
var el = document.createElement('iframe');
el.style.display = 'none';
document.body.appendChild(el);
var win = el.contentWindow;
document.body.removeChild(el);
return win;
}
function detectGlobals() {
var iframe = getIframe();
var ret = Object.create(null);
for (var prop in window) {
if (!(prop in iframe)) {
ret[prop] = window[prop];
}
}
return ret;
}
console.log(detectGlobals());
},
performance: function () {
var t = window.performance.timing;
var lt = window.chrome && window.chrome.loadTimes && window.chrome.loadTimes();
var timings = [];
timings.push({
label: "Time Until Page Loaded",
time: t.loadEventEnd - t.navigationStart + "ms"
});
timings.push({
label: "Time Until DOMContentLoaded",
time: t.domContentLoadedEventEnd - t.navigationStart + "ms"
});
timings.push({
label: "Total Response Time",
time: t.responseEnd - t.requestStart + "ms"
});
timings.push({
label: "Connection",
time: t.connectEnd - t.connectStart + "ms"
});
timings.push({
label: "Response",
time: t.responseEnd - t.responseStart + "ms"
});
timings.push({
label: "Domain Lookup",
time: t.domainLookupEnd - t.domainLookupStart + "ms"
});
timings.push({
label: "Load Event",
time: t.loadEventEnd - t.loadEventStart + "ms"
});
timings.push({
label: "Unload Event",
time: t.unloadEventEnd - t.unloadEventStart + "ms"
});
timings.push({
label: "DOMContentLoaded Event",
time: t.domContentLoadedEventEnd - t.domContentLoadedEventStart + "ms"
});
if(lt) {
if(lt.wasNpnNegotiated) {
timings.push({
label: "NPN negotiation protocol",
time: lt.npnNegotiatedProtocol
});
}
timings.push({
label: "Connection Info",
time: lt.connectionInfo
});
timings.push({
label: "First paint after Document load",
time: Math.ceil(lt.firstPaintTime - lt.finishDocumentLoadTime) + "ms"
});
}
var navigation = window.performance.navigation;
var navigationTypes = { };
navigationTypes[navigation.TYPE_NAVIGATENEXT || 0] = "Navigation started by clicking on a link, or entering the URL in the user agent's address bar, or form submission.",
navigationTypes[navigation.TYPE_RELOAD] = "Navigation through the reload operation or the location.reload() method.",
navigationTypes[navigation.TYPE_BACK_FORWARD] = "Navigation through a history traversal operation.",
navigationTypes[navigation.TYPE_UNDEFINED] = "Navigation type is undefined.",
console.group("window.performance");
console.log(window.performance);
console.group("Navigation Information");
console.log(navigationTypes[navigation.type]);
console.log("Number of redirects that have taken place: ", navigation.redirectCount)
console.groupEnd("Navigation Information");
console.group("Timing");
console.log(window.performance.timing);
console.table(timings, ["label", "time"]);
console.groupEnd("Timing");
console.groupEnd("window.performance");
},
// description of methods
methods: function () {
var m = [];
m.push({
method: 'elementEvents (elem*)',
description: 'Returns all the events associated with the selected element, or given element'
});
m.push({
method: 'requestPerformanceData (grep*)',
description: 'Returns performance data for request. Can grep them',
});
m.push({
method: 'cssReload',
description: 'Reloads all css in the page',
});
m.push({
method: 'saveObjectToFile (data, filename*)',
description: 'Converts to JSON, then saves to file, the provided data',
});
m.push({
method: 'dataurls',
description: 'Print out data URLs for all images / canvases on the page',
});
console.table(m);
},
};
_window.ut = _that;
// globally injected methods
_window.log = Function.prototype.bind.call(console.log, console);
_window.info = Function.prototype.bind.call(console.info, console);
_window.warn = Function.prototype.bind.call(console.warn, console);
_window.error = Function.prototype.bind.call(console.error, console);
// ./globally injected methods
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment