加载AngularJS库后如何运行userscript(/greasemonkey) [英] How to run userscript(/greasemonkey) after AngularJS library is loaded

查看:109
本文介绍了加载AngularJS库后如何运行userscript(/greasemonkey)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想创建一些对angular对象的扩展,以使AngularJS调试更加方便.

I just want to create some extensions to angular object to make AngularJS debugging more convenient.

但是当我运行add userscript时,找不到一个有角度的对象.AngularJS库已加载到标签的底部.

But when I run add userscript, it can't find an angular object. AngularJS library is loaded in the bottom of tag.

UPD :@estus提供了正确的答案,但是如果您要使用chrome,则需要通过 Tampermonkey 扩展名.

UPD: @estus provided right answer, but if you want to use chrome you need to install it via Tampermonkey extension.

您可以在此处找到最终代码段.

You can find final code snippet here.

推荐答案

用户脚本运行时Angular不可用这一事实表明Angular是异步加载的,这对于任何SPA都是很正常的(也请检查 @ run-at 设置为 not 而不是 document-start ,这不是理想的行为).

The fact that Angular is unavailable at the moment when user script runs indicates that Angular is loaded asynchronously, this is quite normal for any SPA (also check that @run-at is not set to document-start, it isn't the desirable behaviour here).

用户脚本的通常解决方法是注意所需的变量:

The usual workaround for user scripts is to watch for the desired variable:

var initWatcher = setInterval(function () {
    console.log('watch');
    if (unsafeWindow.angular) {
        clearInterval(initWatcher);
        init();
    }
}, 100);

function init() {
    console.log('angular', unsafeWindow.angular);
}

如果不需要跨浏览器兼容性,则特定于FF的

If cross-browser compatibility is not required, then FF-specific Object.prototype.watch can be used instead:

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库后如何运行userscript(/greasemonkey)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆