angularjs - 如何在加载 AngularJS 库后运行 userscript(/greasemonkey)

标签 angularjs userscripts

我只是想为 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/

相关文章:

angularjs - AngularJS 中 $http.put 和 $http({method :'PUT' }) 的区别

angularjs - 字形上的点击事件

javascript - $http.get 上的错误处理

javascript - 拦截HTTP请求和响应时,什么时候调用函数request、requestError、response、responseError?

javascript - 是否可以使用 .autocomplete() 的修改?

javascript - Chrome 用户脚本错误 : "Unsafe JavaScript attempt to access frame"

javascript - 如何更改输入中的字体颜色

javascript - 如何在 AngularJS 中启用数据网格?

javascript - 在页面加载时自动按下特定按钮的方法?

google-chrome - Greasemonkey @require 在 Chrome 中不起作用