我想知道一个网站上某些 DOM 元素的所有更改,但不是我的,这样我就可以收到有关 DOM 元素更改的浏览器通知。 如果我不能在网站上编写代码,我怎么能这样做呢? 我想使用这种方法:
// select the target node
var target = document.getElementById('some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
<div id="some-id"></div>
谢谢!
最佳答案
您始终可以将客户端代码添加到任何网站。例如,这是浏览器扩展的主要行为。
但您也可以将代码粘贴到浏览器的控制台(Chrome:Ctrl+Shift+J 或 F12)
在这个例子中,我们将观察 <div id="question-header">
这个 SO 页面的。
// select the target node
var target = document.getElementById('question-header');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
var notification = new Notification("Something has changed!");
}
});
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
然后执行它来测试它是否工作:
var node = document.createElement("b");
var textnode = document.createTextNode("Hello new item");
node.appendChild(textnode);
document.getElementById("question-header").appendChild(node);
关于javascript - 我可以在不是我的网站上添加事件监听器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819114/