我正在尝试记录来自包含嵌入图像的聊天框的消息。
我目前拥有的是能够捕获所有文本,但没有捕获图像。
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length){
//console.log(mutation)
console.log(mutation.addedNodes[0].innerText)
}
})
})
const chat = document.querySelector('div#messagebuffer')
observer.observe(chat, {
childList: true
})
来自节点的 innerHTML 生成类似于
<span class="timestamp">[19:09:36] </span><span><img class="channel-emote" src="https://website.com" title="/image"> Lorem Ipsum <img class="channel-emote" src="https://website.com" title="/image2"></span>
基本上我想解析 html 中的标题值并保持文本看起来像
[19:09:36] /image Lorem Ipsum /image2
假设您只有IMG标签和跨度,您可以执行此类操作。 但是由于文本标记的结构,日期的span
与图像和文本的span
是单独的突变。这意味着,如果您想要在一行中记录日期和文本,您仍然需要修改以下代码。
您可以通过检查跨度的类并基于此刷新数组来轻松做到这一点,但这完全取决于您。 或者,如果可能,您可以将日期span
作为图像和文本的同级。
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
let txtArr = []
if (mutation.addedNodes.length) {
mutation.addedNodes[0].childNodes.forEach((node)=>{
if(node.nodeName == "IMG"){
txtArr.push(node.title)
}else{
txtArr.push(node.wholeText)
}
})
console.log(txtArr.join(''))
}
})
})