Custom property on File instance not cloned when passing to web worker

131 views Asked by At

According to MDN, File objects can be passed to Web Workers and they are properly cloned using the structured cloning algorithm. So far, so good. And this works in all browsers I've tested:

// myFile comes from a form.
// webWorker is the WebWorker object.
webWorker(myFile);  // myFile appears as-is on the other side,
                    // only losing non-enumerable properties
                    // and functions, per the spec.

But this doesn't work:

// myFile comes from a form.
// webWorker is the WebWorker object.
myFile.customIdProperty = 'some string value';
webWorker(myFile);  // myFile appears on the other side,
                    // WITHOUT the 'customIdProperty' property.

Curiously enough, this WORKS:

// myFile is a custom object now.
// webWorker is the WebWorker object.
myFile = {};
myFile.customIdProperty = 'some string value';
webWorker(myFile);  // myFile appears on the other side,
                    // WITH the 'customIdProperty' property.

This occurs in recent versions of Chrome, Firefox, etc. so I don't think it'a browser problem.

Options:

  1. I'm doing something wrong and that is causing that property to be lost when cloning the object.
  2. When cloning a predefined object (like File) and not an object I've created, all custom properties I add get lost because the browser ignores non-standard object properties.
  3. I don't understand the spec and it's obvious custom properties are not cloned when passing objects to Web Workers.

Am I doing something wrong here? Thanks in advance ;))

1

There are 1 answers

1
Kaiido On BEST ANSWER

The File interface has its own serialization steps, which are not the ones of Javascript objects. So yes, your custom properties are lost because these steps don't include grabbing own properties.

  1. Set serialized.[[SnapshotState]] to value’s snapshot state.

  2. Set serialized.[[ByteSequence]] to value’s underlying byte sequence.

  3. Set serialized.[[Name]] to the value of value’s name attribute.

  4. Set serialized.[[LastModified]] to the value of value’s lastModified attribute.