Search code examples
javascriptgreasemonkeyoverridingtampermonkey

Replacing a javascript function inside an object using GreaseMonkey


I am having some troubles finding a way to replace a javascript function that is defined as a property of an object. I had googled it for 2 days and looked at all the questions in stack overflow that are related to overriding a function with javascript, but none of the solution worked. I currently have a webpage (http://gefs-online.com if it helps), and there is an object called "multiplayer" that is declared somewhere like that:

var multiplayer = window.multiplayer || {};

After that, there are some properties under multiplayer that are declared like that:

multiplayer.nbUsers = 0;
multiplayer.users = {};
multiplayer.visibleUsers = {};
multiplayer.minUpdateDelay = 500;
multiplayer.updateTimeout = null ;
multiplayer.hearbeatTimeout;
multiplayer.hearbeatLife = 9000;
multiplayer.userLife = 10000;
multiplayer.userHalfLife = 4000;
multiplayer.mapUpdatePeriod = 10000;
multiplayer.myId = '';
multiplayer.lastRequest = null ;
multiplayer.lastRequestTime = 0;
multiplayer.localTime = new Date().getTime();
multiplayer.farVisibilityRange = 10000;
multiplayer.lowVisibilityRange = 1000;
multiplayer.nearVisibilityRange = 20;
multiplayer.chatMessage = '';
multiplayer.chatMessageId = 0;
multiplayer.on = false;
multiplayer.started = false;
multiplayer.callsignPlacemarkAltitude = 4;
multiplayer.updateFunctions = [];
multiplayer.init = function() {};

The function I'm willing to override is multiplayer.loadModel() that is declared like that:

multiplayer.loadModel = function(oPlayer, oData, lod, callbackFunction) {
    ... //the code of the function
};

Now I want to override that function using GreaseMonkey, but without success. I can't use the regular method of unsafeWindow - because it is not working, and even if it worked, only firefox supports it.

I have read all the questions that are related to the subject, but still didn't find anything, so please don't rate it down.

Thanks to whoever helps me.

UPDATE: I tried again implementing the unsafeWindow like that:

unsafeWindow.multiplayer.loadModel = function (oPlayer, oData, lod, callbackFunction) {
    console.log ("loadModel()");
}

But it only says : "ReferenceError: unsafeWindow is not defined"


Solution

  • Eventually, the ==UserScript== definition was wrong. When using Greasemonkey (Firefox), it should be like this:

    // @grant        none
    

    But when using Tampermonkey/ViolentMonkay (Chrome/Opera) it should be like this:

    // @grant        unsafeWindow