javascript - 更改传递给 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
触发错误不同的名称?
解决方案
Blob()
接受一个选项对象作为它的第二个参数,它可以指定两个属性type
和endings
.
var newBlob = new Blob(array, {type: '', endings: 'transparent'});
在您的第一个工作示例中,您使用简写符号定义此对象,因为您的变量已命名type
并Blob()
需要一个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()
无论变量名称如何,您在调用中声明键时使用的变量名称都是相同的。
推荐阅读
- reactjs - Babel 打字稿预设不与反应预设一起使用
- javascript - 开玩笑如何确保我得到一个字符串值?
- python - 如何在服务之间安全地存储和传递第三方服务的密码?
- python - Python时间戳范围以间隔返回
- mpi - OpenMPI mpirun 在给出“failed-daemon-launch”错误后挂起
- swift - 使 NSAttributedString 符合 Codable 会引发错误
- android - 如何为 List 实现 parcelable
在科特林 - https - 如何在 GCP / Cloud DNS / HTTPS 应用程序中限制对小用户社区(IAM 用户)的访问
- reactjs - React Native:钩子只能在函数组件的主体内部调用
- java - 如何为 SCTP 编写内核补丁以修复已使用的地址