0

There's a website I use written in some mighty fine javascript. Hardly any globals, closures everywhere and it uses strict mode. This is making it really hard to inject my own functionality into the website.

The website client objects are initialised in a jQuery.ready() call:

$(window).ready(function () {
    var a, b, c, d;

    // Setup global data [...]
    // Setup configuration [...]

    a = GlobalFoo.ConstructorA();
    b = GlobalFoo.ConstructorB(a);
    // Really wish I could put stuff here
    c = GlobalFoo.ConstructorC(a, b);
    d = GlobalFoo.ConstructorD(b, c);
    // etc.
});

How can I, for example, replace b.someMethod() with my own code before the other constructors are called?

Can I stop the ready event from happening or replace it with my own code? Since it's quite small I can just duplicate a modified version in my code.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
AnnanFay
  • 9,573
  • 15
  • 63
  • 86

1 Answers1

2

After a bit more searching I found this wonderful page by dindog. There is also this page on the GreaseSpot wiki describing @run-at.

@run-at allows your userscript to run before all other code. The beforescriptexecute event allows you to check each script before it executes. You can then skip or modify it.

My final solution is:

// ==UserScript==
// @name        ...
// @description ...
// @namespace   ...
// @include     ...
// @version     1
// @run-at      document-start
// @grant       none
// ==/UserScript==

(function (w) {
    // Remove the current jQuery ready code
    function pre_script_execute_handler (e) {
        var target = e.target;
        if (target.innerHTML.indexOf("$(window).ready(") != -1) {
            console.log('Removed ready');
            e.preventDefault();
            e.stopPropagation();
            addReady();
        }
    }
    w.addEventListener('beforescriptexecute', pre_script_execute_handler);

    // Add new jQuery ready code
    function addReady () {
        console.log('Adding new ready');
        w.$(window).ready(function () {
            console.log('Our ready called');
        });
    }


}) (unsafeWindow);
AnnanFay
  • 9,573
  • 15
  • 63
  • 86
  • @BrockAdams I searched SO and google but did not notice that post. I may have ignored it because of the very vague question title. I would not go so far as saying the post by dindog is derived from your SO post as the code structure appears very different. – AnnanFay Sep 29 '13 at 01:04