【问题标题】:How to check if JavaScript object was created in the current window or another window?如何检查 JavaScript 对象是在当前窗口还是另一个窗口中创建的?
【发布时间】:2023-02-08 03:04:56
【问题描述】:

假设我有一个对象 OtherObj 在窗口 OtherWindow 中创建,它不同于当前的 ThisWindow

const ThisWindow = window;
const ThisObj = ThisWindow.history;

const OtherWindow = window.open();
const OtherObj = OtherWindow.history;

console.log(ThisObj instanceof Object); //true
console.log(OtherObj instanceof Object); //false
console.log(OtherObj instanceof OtherWindow.Object); //true, but this works only if I already have a reference to OtherWindow

现在想象一下,如果我仅有的OtherObj 的引用,有没有办法获取用于创建它的窗口?也许OtherObj 上有一个属性保存了对创建它的窗口的引用?

我目前正在尝试想出一种使用 instanceof 运算符的跨窗口方式。正如您在代码示例中看到的,如果变量指向在当前窗口之外创建的对象,[variable] instanceof Object 将返回false

你们中的一些人可能会说只使用 OtherObj instanceof OtherWindow.Object(它返回 true),但这只有在我已经有对 OtherWindow 的引用时才有效。我的问题是假设我还没有对OtherWindow 的引用。

OtherObj 上的某处是否有指向创建它的窗口的属性?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    简短回答:

    const OtherWindow = OtherObj.constructor.constructor('return window')();
    

    长答案:

    因为大多数东西在 JavaScript 中都是一个对象,所以您可以使用 Object.getPrototypeOf(ObjectIn).constructor 从对象原型访问它们的构造函数。但是因为原型链ObjectIn.constructor有同样的效果。
    因为那个构造函数是一个函数,所以它的构造函数是Function。一旦我们有了Function,我们就可以使用Function('return ...')()从那个窗口访问所有内容。

    因此,获取 Function 的实现可能如下所示:

    const getFunction = (ObjectIn) => {
      // Get ObjectIn's constructor
      const ObjectInConstructor = ObjectIn.constructor;
      // Get Function
      return ObjectInConstructor.constructor;
    };
    
    const getObject = (ObjectIn) => {
      const Function = getFunction(ObjectIn);
      return Function('return Object')();
    };
    
    const OtherWindowObject = getObject(OtherObj);
    const OtherWindow = getFunction(OtherObj)('return window')();
    

    因为 StackOverflow 的 HTTP 标头不允许 open(),所以我创建了一个 fiddle 来演示。

    【讨论】:

    • 非常聪明!不能将整个事情简化为以下内容:const OtherWindow = OtherObj.constructor.constructor('return window')();
    猜你喜欢
    • 2015-10-13
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多