我的目的是监视带有 Chrome 扩展程序的网页。网页由 Ajax comet push 或 Lightstreamer 更新。例如,如果某个值已达到某个阈值,则该想法是生成警报或其他动作。根据其他答案,我确实创建了以下 chrome 扩展代码,将更改的内容写入控制台:
清单.json:
{
"name": "ContentChangeObserver",
"version": "1.0",
"description": "Capture changes on webpage content",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"permissions": ["webRequest", "webRequestBlocking","contextMenus", "tabs",
"<all_urls>"],
"manifest_version": 2
}
内容脚本.js:
var i=0;
// Create a MutationObserver to handle events
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
i++;
if(i > 100) {
i=0;
console.log("mutation.target.textContent: " + mutation.target.textContent);
console.log("mutation.target.attributeName: " + mutation.target.attributeName);
console.log("mutation.target.type: " + mutation.target.type);
console.log("mutation.target.nodeId: " + mutation.target.nodeId);
console.log("mutation.target.baseURI: " + mutation.target.baseURI);
console.log("mutation.target.nodeName: " + mutation.target.nodeName);
console.log("mutation.target.nodeType: " + mutation.target.nodeType);
console.log("mutation.target.nodeValue: " + mutation.target.nodeValue);
console.log("mutation.target.parentElement: " + mutation.target.parentElement);
}
});
});
// Start observing all events in document and its descendants
observer.observe(document, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
到目前为止,它几乎可以正常工作,我看到所有更改的内容(例如在http://demos.lightstreamer.com/MonitorDemo/上)。
“if (i>100)...”只是为了避免在控制台日志中输出过多。
但我不知道如何找出已更改的特定值(例如http://demos.lightstreamer.com/MonitorDemo/上“Free Heap”的值),因为没有 Ids 或其他元素设置为区分不同的值。我知道我可以为 MutationObserver 设置过滤器,但我不知道我可以过滤什么来获得例如“空闲堆”值。
这里有一些控制台日志:
mutation.target.textContent: 128
mutation.target.attributeName: undefined
mutation.target.type: undefined
mutation.target.nodeId: undefined
mutation.target.baseURI: http://demos.lightstreamer.com/MonitorDemo/
mutation.target.nodeName: DIV
mutation.target.nodeType: 1
mutation.target.nodeValue: null
mutation.target.parentElement: [object HTMLTableCellElement]
mutation.target.textContent: 1,603,282,363
mutation.target.attributeName: undefined
mutation.target.type: undefined
mutation.target.nodeId: undefined
mutation.target.baseURI: http://demos.lightstreamer.com/MonitorDemo/
mutation.target.nodeName: DIV
mutation.target.nodeType: 1
mutation.target.nodeValue: null
mutation.target.parentElement: [object HTMLTableCellElement]