Home > Blockchain >  How to check if JavaScript object was created in the current window or another window?
How to check if JavaScript object was created in the current window or another window?

Time:06-19

Let's say I have an object OtherObj that was created in a window OtherWindow which is different from the current one 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 method only if I already have a reference to OtherWindow

Now imagine if I only have a reference to OtherObj, is there a way to get the window that was used to create it? Maybe there is a property on OtherObj that holds a reference to the window it was created in?

I'm currently trying to come up with a cross-window way to use the instanceof operator. As you can see in the code example, [variable] instanceof Object will return false if the variable is pointing to an object created outside of the current window.

Some of you might say to just use OtherObj instanceof OtherWindow.Object (which returns true), but that only works if I already have a reference to OtherWindow. My question is assuming I do not already have a reference to OtherWindow.

Is there a property somewhere on OtherObj that points to the window that created it?

CodePudding user response:

Because most things are an object in JavaScript you can access their constructor with Object.getPrototypeOf(...).constructor.
And because that constructor is a function, its constructor is Function. And once we have Function we can access everything from that window with Function('return ...')().

So an implementation to get Function could be as follows:

const getFunction = (ObjectIn) => {
  // Get the prototype of ObjectIn  
  const ObjectInPrototype = Object.getPrototypeOf(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')();

Because StackOverflow's HTTP headers don't allow open() I've created a fiddle to demonstrate.

  • Related