Create structured clone of Proxy
14:17 22 May 2017

I have a class that returns a Proxy from the constructor. When I try to store instances of this class in IndexedDB, or send the object using window.postMessage(), I receive an error stating that the object could not be cloned. It appears that the structured clone algorithm cannot handle Proxy objects.

The following code demonstrates the error:

class MyClass {
  constructor() {
    return new Proxy(this, {
      set(target, prop, val, receiver) {
        console.log(`"${prop}" was set to "${val}"`);
        return Reflect.set(target, prop, val, receiver);
      }
    });
  }
}

const obj = new MyClass;

try {
  window.postMessage(obj,'*');
} catch(err) {
  console.error(err);

}

Can anyone suggest a workaround for this problem? I see two potential solutions, but I don't know how I might implement them:

  1. Do not return a Proxy from the constructor, but maintain the Proxy functionality within the class declaration somehow.

  2. Alter the Proxy instance so that it works with the structured clone algorithm.

The following, simpler code also demonstrates the structured clone error:

const p = new Proxy({}, {});
window.postMessage(p, '*');

javascript es6-proxy