首页 > 解决方案 > 更改传递给 blob 选项对象的变量名称(类型)时出现 DOMException 错误

问题描述

这个js代码工作正常:

var text="copy me"
var type = 'text/plain';
var blob = new Blob([text], { type });
var data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data)

但是,如果我将type变量名称更改为其他名称,即使没有对代码逻辑或语法进行任何更改,代码也会引发错误,例如:

var text="copy me"
var anotherName= 'text/plain';
var blob = new Blob([text], { anotherName});
var data = [new ClipboardItem({ [anotherName]: blob })];
navigator.clipboard.write(data)

我得到的错误:

Uncaught (in promise) DOMException: Type text/plain does not match the blob's type 

为什么使用与type触发错误不同的名称?

标签: javascript

解决方案


Blob()接受一个选项对象作为它的第二个参数,它可以指定两个属性typeendings.

var newBlob = new Blob(array, {type: '', endings: 'transparent'});

在您的第一个工作示例中,您使用简写符号定义此对象,因为您的变量已命名typeBlob()需要一个type属性,所以该符号有效。

var type = 'text/plain';
var blob = new Blob([text], { type });
// equivalent to: var blob = new Blob([text], { type: type });

但是在您的第二个示例中,您正在创建一个具有Blob()无法识别的属性名称的选项对象,并且您根本没有指定type

var anotherName= 'text/plain';
var blob = new Blob([text], { anotherName});
// equivalent to: var blob = new Blob([text], { anotherName: anotherName });

您可以通过在选项对象中显式声明键来解决此问题。

var anotherName= 'text/plain';
var blob = new Blob([text], { type: anotherName});

注意:new ClipboardItem()无论变量名称如何,您在调用中声明键时使用的变量名称都是相同的。


推荐阅读