Skip to content

Instantly share code, notes, and snippets.

@jkjustjoshing
Last active December 6, 2021 16:32
Show Gist options
  • Save jkjustjoshing/32a3a9cb10449ea009d1 to your computer and use it in GitHub Desktop.
Save jkjustjoshing/32a3a9cb10449ea009d1 to your computer and use it in GitHub Desktop.
Angular $inject userscript.
// ==UserScript==
// @name AngularJS Injector
// @namespace http://joshkra.me/
// @version 0.1
// @description Binds $inject method to window
// @author jkjustjoshing
// @match *://*/*
// ==/UserScript==
// This userscript creates an $inject() method on the window object that can be used to
// obtain a service reference from the console.
// To install in Chrome, save this file locally. Go to chrome://extensions, and drag-and-drop
// the file in the browser window.
(function() {
var method = function() {
var counter = 0;
var interval = setInterval(function () {
if(window.angular) {
bind();
}
if(window.angular || counter > 10) {
clearInterval(interval);
}
counter++;
}, 500);
function bind () {
var injector = window.angular.element(document.body).injector();
window.$inject = function(serviceString) {
var service = injector.get(serviceString);
if(!window[serviceString]) {
window[serviceString] = service;
}
return service;
};
if (!window.$scope) {
var elementGetter;
Object.defineProperty(window, '$scope', {
configurable: true,
enumerable: true,
set: function (element) {
if (typeof element === 'function') {
elementGetter = element;
}
},
get: function () {
if (elementGetter) {
return window.angular.element(elementGetter()).scope();
}
return null;
}
});
}
var $rootScope = injector.get('$rootScope');
$rootScope.countWatchers = function () {
var q = [this], watchers = 0, scope;
while (q.length > 0) {
scope = q.pop();
if (scope.$$watchers) {
watchers += scope.$$watchers.length;
}
if (scope.$$childHead) {
q.push(scope.$$childHead);
}
if (scope.$$nextSibling) {
q.push(scope.$$nextSibling);
}
}
return watchers;
};
var isOn = false, $oldDigest;
$rootScope.profileDigest = function (_isOn_) {
if (!isOn && _isOn_) {
// Turning on
$oldDigest = $rootScope.$digest;
$rootScope.$digest = function () {
console.time('$digest');
$oldDigest.apply($rootScope);
console.timeEnd('$digest');
};
}
else if (isOn && !_isOn_) {
// Turning off
$rootScope.$digest = $oldDigest;
$oldDigest = null;
}
isOn = _isOn_;
};
}
};
var script = document.createElement("script");
script.textContent = "(" + method.toString() + ")();";
document.body.appendChild(script);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment