Chaos Project

Game Development => General Discussion => Topic started by: Heretic86 on April 27, 2021, 07:42:29 pm

Title: Javascript postMessage loses Class Instance Properties
Post by: Heretic86 on April 27, 2021, 07:42:29 pm
Hopefully this is an "easy" one.

I have a page that creates an Instance of a Class.  Then the Class Instance is sent to another page using page.postMessage();  When I receive the data on the other page, and I check the received data to see if the object is an Instance of the Class, it always fails, presumably because I am missing a step.

Properties Page:
class MyClass {
  constructor(name, value){
    this.name = name;
    this.value = value;
  }
}
const foo = new MyClass("bob", 123);
window.postMessage( { myMsg : foo });
function messageListener(msg){
  console.log(msg.data.myMsg instanceof MyClass); // Always returns false
}

I left a lot of code out of the examples but basically using Modules so the same class constructor is available on both pages.

I would like to be able to check the data on the receiving page to see if the object is an instance of the class.

What am I doing wrong?  Most importantly, how can I check on the receiving page to see if the received data is an instance of the class?
Title: Re: Javascript postMessage loses Class Instance Properties
Post by: Blizzard on May 07, 2021, 10:07:09 am
Try printing just:

console.log(msg.data);

to see if you actually have the proper data/object inside.