How to run userscript(/greasemonkey) after AngularJS library is loaded

柔情痞子 提交于 2020-12-01 07:52:48

问题


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

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

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.


回答1:


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);
}

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);
}


来源:https://stackoverflow.com/questions/31968159/how-to-run-userscript-greasemonkey-after-angularjs-library-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!