From the spec, I think it would be something like
function canBeCloned(val) {
if(Object(val) !== val) // Primitive value
return true;
switch({}.toString.call(val).slice(8,-1)) { // Class
case 'Boolean': case 'Number': case 'String': case 'Date':
case 'RegExp': case 'Blob': case 'FileList':
case 'ImageData': case 'ImageBitmap': case 'ArrayBuffer':
return true;
case 'Array': case 'Object':
return Object.keys(val).every(prop => canBeCloned(val[prop]));
case 'Map':
return [...val.keys()].every(canBeCloned)
&& [...val.values()].every(canBeCloned);
case 'Set':
return [...val.keys()].every(canBeCloned);
default:
return false;
}
}
Note this has some limitations:
- I can't check if an object has a [[DataView]] internal slot
{}.toString
is not a reliable way to get the [[Class]], but is the only one.
- Other specifications may define how to clone additional kinds of objects
So it may be more reliable to attempt to run the algorithm, and see if it produces some error:
function canBeCloned(val) {
try {
window.postMessage(val,'*');
} catch(err) {
return false;
}
return true;
}
Note if you have a message
event listener, it will be called. If you want to avoid this, send the value to another window. For example, you can create one using an iframe:
var canBeCloned = (function() {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var win = iframe.contentWindow;
document.body.removeChild(iframe);
return function(val) {
try { win.postMessage(val, '*'); }
catch(err) { return false; }
return true;
};
})();
DATA_CLONE_ERR
exception that it throws if it's not valid? If you catch an exception, the object is not serializable, otherwise it is. – Forbornewindow.postMessage
depending on the context, but for consistency I'd like it to report an error if the data isn't compatible with the structured clone algorithm. – Demit