chrome.runtime.sendMessage 和 new FormData()
chrome.runtime.sendMessage 是Chrome扩展程序API中的一个方法,可用于背景脚本和内容脚本之间的消息传递。
new FormData() 提供了一种方便的方式来构建表单数据集。
在Chrome插件中,在 background.js 和 content.js 进行通信时使用了使用new FormData(),结果数据传不过去。
FormData的数据不能直接查看,需要便利FormData对象中的键值对。
function printFormData(formData) {const result = {};for (const [key, value] of formData.entries()) {if (result[key]) {// 处理重复键(如多文件上传)result[key] = Array.isArray(result[key])? [...result[key], value]: [result[key], value];} else {result[key] = value;}}return result;
}
background.js 和 content.js中代码。
const formData = new FormData()
formData.append('name', 'joe')
formData.append('age', 18)
console.log(formData, 'formData');
console.log(printFormData(formData), 'printFormData(formData)');chrome.runtime.sendMessage({body: formData
}, (response) => {console.log(response);
});
可以看到,代码中先添加了数据,再输出formData,但输出语句没有看到数据,需要遍历键值对查看,将数据通过 sendMessage 进行传递。
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {console.log(request.body, 'request.body')console.log(printFormData(request.body), 'printFormData(request.body)')
})
遍历 request.body 时报不可迭代的错误,说明 request.body 中没有数据。
这是因为在 chrome.runtime.sendMessage 传递 FormData 时,FormData 不能被序列化为 JSON,而 Chrome 扩展的消息机制会自动尝试序列化消息内容。如果你直接传递 FormData,它会变成一个普通的对象,最终收到的就是 {}。
所以不能直接传 FormData ,在需要用到 FormData 的页面进行组装。