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

前端 未结 1 1582
猫巷女王i
猫巷女王i 2021-02-11 04:06

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. Ang

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-11 04:40

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

    0 讨论(0)
提交回复
热议问题