如何从浏览器控制台模拟javascript新日期到return不同日期

How to mock javascipt new Date to return different date from browser console

我使用的一个网站在不同的日期显示不同的内容。在 JavaScript 中,它使用 new Date() 来确定当前日期,它使用它来确定要显示的内容。

如果我想查看不同日期的内容,我可以更改我的系统时间。然而,这很乏味并且会干扰其他应用程序。我想弄清楚是否有一些代码可以 运行 在浏览器的 javascipt 控制台中模拟 new Date() 到 return 我选择的日期

我看到有一些问题在开玩笑地讨论在 Date 上创建间谍,但我没有在我的浏览器控制台中看到模拟这个的方法

可以用您自己的函数替换 Date 函数来提供您想要的结果,但除非您编写浏览器扩展程序,否则在页面使用它之前执行此操作将很棘手。

基本位是(见评论):

// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
    // Called via `new`?
    if (!new.target) {
        // No, just pass the call on
        return OriginalDate(...args);
    }
    // Determine what constructor to call
    const ctor = new.target === Date ? OriginalDate : new.target;
    // Called via `new`
    if (args.length !== 0) {
        // Date constructor arguments were provided, just pass through
        return Reflect.construct(ctor, args);
    }
    // It's a `new Date()` call, mock the date we want; in this
    // example, Jan 1st 2000:
    return Reflect.construct(ctor, [2000, 0, 1]);
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
    value: OriginalDate.length,
    configurable: true
});

// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
    // Called via `new`?
    if (!new.target) {
        // No, just pass the call on
        return OriginalDate(...args);
    }
    // Determine what constructor to call
    const ctor = new.target === Date ? OriginalDate : new.target;
    // Called via `new`
    if (args.length !== 0) {
        // Date constructor arguments were provided, just pass through
        return Reflect.construct(ctor, args);
    }
    // It's a `new Date()` call, mock the date we want; in this
    // example, Jan 1st 2000:
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
    value: OriginalDate.length,
    configurable: true
});

console.log("new Date()", new Date());
console.log("new Date(2021, 7, 3)", new Date(2021, 7, 3));

您可以使用它在加载之前修改内容: https://developer.chrome.com/docs/extensions/reference/webRequest/

有一个我没有用过的扩展程序也许可以做到这一点: https://chrome.google.com/webstore/detail/page-manipulator/mdhellggnoabbnnchkeniomkpghbekko?hl=en