在调用对象函数之前,覆盖外部脚本中的对象函数

Overwrite an object function from an external script before it is called

本文关键字:对象 函数 外部 脚本 覆盖 调用      更新时间:2023-09-26

我正试图编写一个Greasemonkey脚本或Userscript来修复网站中的一个错误,该错误处理对象的错误函数。我可以手动解决这个问题,方法是在生成函数原型的代码行添加断点,并使用js控制台手动覆盖函数原型。然而,我不认为有任何方法可以用代码做到这一点。外部脚本加载在html主体的末尾,但问题代码在同一脚本中执行。

有没有什么方法可以将javascript代码注入到页面中,这样当创建Ft.prototype.J时,我就可以立即修改它?问题是代码也被混淆和缩小了,所以我不确定它的一半是什么。

以下是代码的基本概要:

//What does this do?????
function A(a, b) {
    function c() {}
    c.prototype = b.prototype;
    a.f = b.prototype;
    a.prototype = new c;
    a.prototype.constructor = a
}
function Ft(a, b) {
    $.call(this, b);
    //some stuff
}
//doing something with jQuery?
A(Ft, $);
Ft.prototype.J = function (a) {
   //modifies the DOM content
};
//Code soon after that calls some object.J

如果我将代码Ft.prototype.J = function() {} //my own function添加到我的防油精脚本中,它会像预期的那样返回错误Ft not defined。但是,如果我在加载结束时执行这一行,那么损坏的函数已经运行,DOM也已经被感染。

谢谢。

我认为您可以用getters/ssetters和Object.defineProperty执行一些魔术,因为函数是全局声明的:

(function() {
    var Ft;
    function myJ() {
        // do whatever YOU want to do
    }
    Object.defineProperty(window, "Ft", { // use unsafeWindow in GM?
        configurable: true,
        enumerable: true,
        get: function() { return Ft; },
        set: function(n) {
            // Hah, we've catched the function declaration!
            Ft = n;
            // just making it non-writable would lead to an exception
            Object.defineProperty(Ft.prototype, "J", {
                get: function() { return myJ; },
                set: function() { /* ignore it! */ }
            });
        }
    });
})();

现在,如果有人执行了你在问题中发布的代码,那么setter就会被调用,你可以随心所欲地使用这些值。

不确定,但您基本上可以编写一个计时器代码,检查Ft对象是否可用,然后修改函数,如

var interval = setInterval(function() {
    if (Ft) {
       Ft.prototype.J = function() {} //my own function
       clearInterval(interval)
    }
}, 0);