javascript - 我可以在不是我的网站上添加事件监听器吗?

标签 javascript jquery

我想知道一个网站上某些 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+JF12)

在这个例子中,我们将观察 <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/

相关文章:

javascript - Angular 一次性绑定(bind)无法等待 bool 条件

javascript - 单击按钮时更改数组中的文本

php - 使用 jQuery 选择 pdf url

javascript - 在 ui-router 中的 ng-click 上设置事件类

javascript - 为什么日期时间选择器中的日期没有突出显示?

javascript - 主干模型扩展

javascript - JavaScript 中的函数与对象以及没有函数的实例化

javascript - 无法在 google api 上获取标记

javascript - Js limitter 一次带弹窗的 Action

javascript - jQuery 仅在下拉菜单中选择父 li