我只是想为 Angular 对象创建一些扩展,以使 AngularJS 调试更加方便。
但是当我运行 add userscript 时,它找不到 Angular 对象。 AngularJS 库加载在标签底部。
UPD:@estus 提供了正确的答案,但如果您想使用 Chrome,则需要通过 Tampermonkey 安装它扩展名。
您可以找到最终的代码片段here .
最佳答案
事实上,当用户脚本运行时,Angular 不可用,这表明 Angular 是异步加载的,这对于任何 SPA 来说都是很正常的(还要检查 @run-at 是否没有设置为 document-start
,这不是理想的行为)。
用户脚本的通常解决方法是监视所需的变量:
var initWatcher = setInterval(function () {
console.log('watch');
if (unsafeWindow.angular) {
clearInterval(initWatcher);
init();
}
}, 100);
function init() {
console.log('angular', unsafeWindow.angular);
}
如果不需要跨浏览器兼容性,则 FF 专用 Object.prototype.watch可以使用:
unsafeWindow.watch('angular', function (prop, oldVal, newVal) {
console.log('watch');
if (newVal) {
unsafeWindow.unwatch('angular');
// angular is still undefined ATM, run init() a bit later
setTimeout(init);
}
return newVal;
});
function init() {
console.log('angular', unsafeWindow.angular);
}
关于angularjs - 如何在加载 AngularJS 库后运行 userscript(/greasemonkey),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968159/